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;   proxy_pass; 

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 {

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

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

Since domain name ( 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.


No comments: