Mastering Nginx

(Ron) #1
Appendix B

[ 273 ]

Before NGINX had the try_files directive, there would be no choice but to use


if to test for the existence of the URI:


if (!-e $request_filename) {

rewrite ^/(.*)$ /index.php?q=$1 last;

}

Don't do this. You may see configurations on the Internet that recommend you do


exactly this, but they are outdated or are copies of an outdated configuration. While


not strictly a rewrite rule, because try_files belongs to the core http module, the
try_files directive is much more efficient at performing this task and this is exactly


what it was created for.


Rule #2: Replace matches against REQUEST_URI with a location


Many Apache rewrite rules are made to be placed into .htaccess files because,


historically, users would most likely have access to these files themselves. A


typical shared hoster would not enable their users direct access to the virtual host
configuration context responsible for their website, but would instead offer the ability


to place nearly any kind of configuration into an .htaccess file. This led to the
situation we have today, with a proliferation of .htaccess-file-specific rewrite rules.


While Apache also has a Location directive, it is rarely used to solve the problem
of matching against the URI because it may only be used in either the main server


configuration or the configuration of a virtual host. So, instead we will see a
proliferation of rewrite rules that match against REQUEST_URI:


RewriteCond %{REQUEST_URI} ^/niceurl

RewriteRule ^(.*)$ /index.php?q=$1 [L]

This is best handled in NGINX by using a location:


location /niceurl {

include fastcgi_params;

fastcgi_index index.php;

fastcgi_pass 127.0.0.1:9000;

}
Free download pdf