in Web server by (13.8k points) recategorized by
0 like 0 dislike

Me interest location directives priority in Nginx. What order work location directives in Nginx web server?

nginx location priority

1 Answer

0 like 0 dislike
by (13.8k points) edited by

Read HTTP core module docs:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

Example from documentation:

location  = / {
  # matches the query / only.
  [ configuration A ] 
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 

I.e., location directives of Nginx fires in next order:

  1. = (exactly)
    location = /path
  2. ^~ (forward match)
    location ^~ /path
  3. ~ (regular expression case sensitive)
    location ~ /path/
  4. ~* (regular expression case insensitive)
    location ~* .(jpg|png|bmp)
  5. / (any, what begin with /)
    location /path

There is a handy online testing tool for location priority now: location priority testing online.

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.