Nginx alias try_files and PHP
Web servers map URIs to pathnames, and the simplest mapping is concatenating the document root and the URI, which is managed using the root directive.
Sometimes, part of the URI needs to be removed before performing a concatenation, in which case the alias directive may be useful.
This article addresses issues from using the alias directive with the try_files directive and with php-fpm.
In this article, our URIs begin with a value /prefix, e.g. /prefix/foo.html. The document root is /path/to/root such that the previously mentioned URI is a static file located at /path/to/root/foo.html. Clearly the root directive cannot be used in this case.
location /prefix {
Ψalias /path/to/root;
Ψ.
Ψ.
Ψ.
}
The above location block can process URIs that begin with /prefix (e.g. /prefix/foo.html). The alias directive causes the value of the location directive to be removed from the front of the URI and substituted with the value of the alias directive. The constructed pathname is available as the variable $request_filename.
For example:
location /prefix/ {
Ψalias /path/to/root/;
Ψ.
Ψ.
Ψ.
}
Generally, the next statement in the location block would be try_files. However, because of a long standing issue we tend to avoid using try_files and alias together. So an if statement is used instead, but first read this application note.
Combining alias with a PHP location block might look something like this:
location ^~ /prefix/ {
Ψalias /path/to/root/;
Ψif (!-e $request_filename) { rewrite ^ /prefix/index.php last; }
Ψlocation ~ \.php$ {
ΨΨif (!-f $request_filename) { return 404; }
ΨΨinclude fastcgi_params;
ΨΨfastcgi_param SCRIPT_FILENAME $request_filename;
ΨΨfastcgi_pass ...;
Ψ}
}
The ^~ modifier is used with this prefix location to avoid unwanted side-effects from other regular-expression location blocks.