Home  >  Q&A  >  body text

web - nginx location search algorithm problem! ?

First post my server configuration:

server {
    listen 80;
    server_name xxx; 
    # 1
    location = /favicon.ico {
        root /home/www-data/static;
        rewrite (.*) /img/designs/admin-favicon.ico;
    }
    #2
    location = /robots.txt {
        root /home/www-data/static;
        rewrite (.*) /admin-robots.txt;
    }
    # 3
    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://127.0.0.1:22222;
     }
}

The official location search path priority and algorithm description are as follows:

To find location matching a given request, nginx first checks
locations defined using the prefix strings (prefix locations). Among
them, the location with the longest matching prefix is ​​selected and
remembered. Then regular expressions are checked, in the order of
their appearance in the configuration file. The search of regular
expressions terminates on the first match, and the corresponding
configuration is used. If no match with a regular expression is found
then the configuration of the prefix location remembered earlier is
used.

According to my understanding, the algorithm when Nginx searches should be like this:

  1. Search the location according to the request prefix for the longest common prefix match (if there is an = modifier, the location will be matched directly, if there is a ^~ modifier, the location will be used directly), remember the longest matching location.
  2. Continue to search for regular matches in the configuration order. If there is one, match the first matched location directly, otherwise use the ordinary longest location

In other words, according to my configuration, when the browser requests /favicon.ico, it should directly and accurately match
1 is correct, but it matches 3 every time.

I would like to ask everyone here, is there any deviation in my understanding of Nginx location? Then why does my configuration result like this?

黄舟黄舟2712 days ago950

reply all(1)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-16 17:29:37

    After configuring it according to the original poster’s method, I can get to #1 here.
    I think it may be a CDN cache issue. The author can try rewriting other files or try it in an environment without CDN.

    reply
    0
  • Cancelreply