Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match question mark "?" as regexp on nginx.conf location

Tags:

regex

nginx

I'd like to match question mark "?" as regexp on nginx.conf location.

For example, a URL pattern which I'd like to match is /something?foo=5 or /something?bar=8 (parameter only changeable).

Because nginx adopts RCPE, I can write the location on nginx.conf as follows:

location ~ ^/something\?.* {
}

The above doesn't match the URL pattern. How can I do that?

Also, the following is not my expectation.

location ~ ^/something?.* {
}

It'll match /something_foo_bar_buzz that I don't expect.

like image 309
bekkou68 Avatar asked Mar 30 '13 01:03

bekkou68


People also ask

How to add location directive in NGINX?

NGINX location directive syntax The NGINX location block can be placed inside a server block or inside another location block with some restrictions. The syntax for constructing a location block is: location [modifier] [URI] { ... ... } The modifier in the location block is optional.

What is location on NGINX?

The location directive within NGINX server block allows to route request to correct location within the file system. The directive is used to tell NGINX where to look for a resource by including files and folders while matching a location block against an URL.

What is regex NGINX?

NGINX allows regexes in multiple parts of a configuration, for example locations, maps, rewrites, and server names. The tester described here is for regexes in locations and maps.

Can NGINX location blocks match a URL query string?

nginx location block doesn't match query string at all. So it's impossible. This directive allows different configurations depending on the URI.


1 Answers

nginx location block doesn't match query string at all. So it's impossible.

Location

This directive allows different configurations depending on the URI.

In nginx, there is a built-in variable $uri, which the location block is matched against. For example, give a request

http://www.example.com/app/login.php?username=xyz&password=secret

the $uri value is this string:

 /app/login.php

and the query_string is stored in nginx variable $args:

username=xyz&password=secret

To do something wrt. query string, you can do something like

if ($args ~ username=xyz) {
   # do something for requests with this query string
}

But be careful, IF is Evil

like image 87
Chuan Ma Avatar answered Oct 19 '22 18:10

Chuan Ma