nginx dynamic settings – part 2

In my previous post re. nginx dynamic settings, I’ve put an example of using variables in the index directive for serving a dynamic main file. This time I want to talk about try_files directive.

In the official examples, linked above, there is a one showing how to provide default place holder image, which is nice, and useful for hard set configurations. Most of the other examples are around internal rewrites to language interpreters.

Now say you host a Drupal multi-site, or WordPress multi-site and want to provide different favicon.ico files or robots.txt per domain, this can come handy. Here is an example:

location /favicon.ico {
    try_files $http_host.favicon.ico favicon.ico =404;
    log_not_found off;
    access_log off;

This way you can provide a default file for all, and specify a unique one for some.

Notice that for favicon.ico this doesn’t really cover it, since themes provide “shortcut icon” tags that override the default favicon. But for robots.txt this is very useful.

How to set dynamic nginx settings using variables

Looking through solutions on the internet, I found that for nginx there are plenty solution for dynamic root directories, headers and environment variables out there.

Today I was asked about using the same application directory with various cached index files, in this case, the determination is based on the domain accessed.

The previous solution used was to create spearate root directories with copies of the same system, which is wrong, just a waste of deployment time and configuration.

A more elegant solution, is to use the $http_host variable, and define a dynamic index file, like this:

index index.$http_host.php index.php index.html;

Now, be aware, this might not always be the best solution. also, most of the times, this will not be the specific setting or variable to use, but the idea is there.