Wednesday, October 31, 2012

nginx: try_files, proxy_pass and rewrite

Situation: serves files locally if not found get it from a proxy server

location ^~ /site {

  try_files $uri $uri.html @proxy;

}

location @proxy {
  resolver 8.8.8.8;   proxy_pass http://mysite.com/; 
}

The prefix "@" specifies a named location. Such locations are not used during normal processing of requests, they are intended only to process internally redirected requests (see error_page, try_files).

To avoid any non-named location to be not processed by external requests try internal.

While passing request nginx replaces URI part which corresponds to location with one indicated in proxy_pass directive. So

location /mymatch {
  proxy_pass http://10.11.12.13;
}

e.g. For the request http://host/mymatch/foo/bar the request to proxy would be http://10.11.12.13/foo/bar stripping the /mymatch from the requested URI.

In the above case there is no replacement because we are named location.

Since domain name (mysite.com) is used and not IP it is required to set the resolved. I have set Goolge's resolver IP.

Difference between try_files and rewrite

try_files sets the internal URI pointer (does not change the URI) and only the last parameter causes an internal redirect.

Since try_files sets the internal pointer a leading slash might be required.

try_files $uri /index.html;

So it will look for <root>/index.html. Otherwise <root>index.html

rewrite directive changes URI in accordance with the regular expression and the replacement string. Directives are carried out in order of appearance in the configuration file.

Flags make it possible to end the execution of rewrite directives.

References:

http://wiki.nginx.org/HttpCoreModule#try_files

http://wiki.nginx.org/HttpCoreModule#location

http://wiki.nginx.org/HttpCoreModule#internal

http://wiki.nginx.org/HttpRewriteModule#rewrite

http://wiki.nginx.org/HttpProxyModule#proxy_pass

No comments: