Ace
Ace

Reputation: 493

NGINX Regex location - Starts with X AND does not contain Y

I have the following location config:

location ~ ^/(trucks|cars|planes|system|tools) {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/htauth_file;
        proxy_set_header Host "server.lan";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass  http://127.0.0.1:8080$request_uri;
}

When anyone makes requests to

/trucks

or

/cars

etc, I want them to be authenticated by the basic auth. But when anyone makes requests to

/trucks?id=123

or

/cars?id=124

then I want no authentication, taken care of a lower location block.

I basically dont want the location to match when there is a question mark in the URI.

Is there a way to modify my pasted config so that it does not match when there is a question mark in the URI?

Upvotes: 1

Views: 9895

Answers (2)

Quinn
Quinn

Reputation: 4504

I suggest the following regex:

^/(trucks|cars|planes|system|tools)(?![^\s?]*\?)

DEMO.

Upvotes: 7

Saleem
Saleem

Reputation: 8978

Try following regex:

location ~ ^/[^?]+ {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/htauth_file;
        proxy_set_header Host "server.lan";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass  http://127.0.0.1:8080$request_uri;
}

It will:

 /cars <--match
 /trucks <--match
 /trucks?id=123 <-- no match

Upvotes: 1

Related Questions