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.

Note:

In most cases, the desired textual substitution occurs at a path element boundary which is delimited by a / character. For correct operation the values of the location and alias directives should either both end in / or neither end in /.

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.

Note:

Specify include files before fastcgi_param directives to avoid those directives being silently overridden by similar directives within the included files.