nginx. Test which location used to process request

2019-03-17 19:34发布

问题:

I'm wondering how do I know if a particular location[s] used to process request in nginx.

E.g.:

# 1
location / {}

# 2
location ~ /[\w\-]+\.html {}

# 3
location ~ /\w+\.html {}

How do I know if URI like /mysite is processed by 3rd location and not 2nd? I tend to use add_header for this matter:

location / {
    add_header location 1;
}

location ~ /(\w+\-)\.html {
    add_header location 2;    
}

location @named {
    add_header location named;
}

And I'd like to know is there a better solution or what do you personally use for debugging purposes?

回答1:

The add_header trick is how I would do it to.

I'm at work right now, so I can't test but you might possibly get something in the logfile i you set the error_log level to:

  • debug: you're nginx needs to be built using --with-debug for this to work, you can check that with the nginx -V command
  • notice: if debug logging isn't enabled


回答2:

If you just want to see which block was used, and don't care about returning otherwise valid results, it might be more straight-forward to use return rather than add_header.

location / {
    return 200 'location 1';
}

location ~ /(\w+\-)\.html {
    return 200 'location 2';    
}

location @named {
    return 200 'location named';
}


回答3:

A word of warning on this approach. I found it's a bad idea to use location as your debug header, since Location is a real header used by the HTTP response 301.

So if (like me) in your testing you end up with this:

HTTP/1.1 301 Moved Permanently
...
Location: http://mydomain.com/banana/
location: banana

Then your browser will freak out and report Duplicate headers received from server. So use locationdebug or something safe.