NGINX If This AND That

NGINX If This AND That

Overview

I was working on an NGINX site recently and came across something odd. NGINX doesn’t allow the ability to check multiple conditionals in a single statement. I wanted to be able to force HTTPS for all directories except two. I thought I could write something like this (psuedo code), but NGINX complained

if ($uri != 'firmware') and ($uri != 'provision') {
    # Force HTTPS
}

Configuration

In the end, I found a hacky way of doing it. This is the code sets prov_test to 0, then checks if the URI is fw or provision. If the URI is fw or provision, it sets prov_test to 1. Prov_test is checked at the end to see if HTTPS should be set or not.

server {
        listen 80;
        server_name fusionpbx;
        set $prov_test 0;
        if ($uri ~* ^.*provision.*$) {
                set $prov_test 1;
        }
        if ($uri ~* ^.*/fw/.*$) {
                set $prov_test 1;
        }
        if ($prov_test != 1) {
                rewrite ^(.*) https://$host$1 permanent;
                break;
        }
Mastodon