Archive for November 2016

Nginx Gotchas: Location and Rewrite Directive

I use Nginx for web server, reverse proxy and load balancer because of its lightweight and easier to configure than other web server application. For example, when I need to set particular vhost to be default, all I have to do is adding or moving default_server parameter at listen directive. That was much easier compared with Apache Httpd. But, sometimes I need to debug my configuration when it misconfigured or didn't run as expected. So these are some gotchas when I debug my Nginx configuration.

Location precedence
I have this experience when some location never accessed, Nginx always use other location when client access it. Turns out I didn't have any idea how Nginx read location precedence at that time, so I dig into its documentation and found out this precedence:
  • ~* uri_pattern
    This configuration will match request with uri_pattern regex case insensitive.
  • ~ uri_pattern
    This configuration will match request with uri_pattern regex case sensitive.
  • = /uri
    This configuration will match request with exact /uri
  • /uri
    This configuration will match uri with prefix /uri (eg. /uri/index.html)
  • ^~ uri_pattern
    This configuration will match with uri_pattern but if the longest matching prefix location has the ^~ modifier then regular expressions are not checked.
  • /
    All other request uri unmatched above pattern will be passed to this location

Rewrite Directive
All you have to do is pay attention on the flag parameter, as described in documentation there are four flags you can use:
  • last
    It stops processing the current set of rewrite directives and starts a search for a new location matching the changed URI;
  • break
    It stops processing the current set of rewrite directives as with the break directive;
  • redirect
    It returns a temporary redirect with the 302 code, used if a replacement string does not start with “http://” or “https://”;
  • permanent
    It returns a permanent redirect with the 301 code.
Once you know how rewrite flag work, it will make you easy to choose which one is appropriate with your situation.