Understanding the Nginx Configuration Inheritance Model

folder_openNginx, Technology
comment14 Comments

The nginx configuration model is a big improvement over the Apache HTTPd one.

But when you dive in deeper there are some quirks to be aware of. Without knowledge of the fundamentals it’s easy to run into situations where you get unexpected behaviour.

To make sure you always know how to wrangle nginx I’ve prepared this post to help you understand how it all works, read on!

To understand the inheritance model of nginx you first need to know that nginx operates with multiple blocks of configuration.

In nginx such a block is referred to as a context, for instance, a configuration directive placed in server context resides within a server { } block just like a directive placed in http context resides in the http { } block.

There are 6 possible contexts in nginx, here in top to bottom order:

  • Global.
  • Http.
  • Server.
  • If.
  • Location.
    • Nested Location.
    • If in location.
    • limit_except.

The default inheritance model is that directives inherit downwards only. Never sideways and definitely never up. This includes scenarios where you rewrite a request internally from one location to another – every directive in the first location is forgotten and only the second location directives apply for the location context.When it comes to inheritance behaviour there are four types of configuration directives in nginx:

  • Normal directive – One value per context, for example: “root” or “index”.
  • Array directive – Multiple values per context, for example: “access_log” or “fastcgi_param”
  • Action directive – Something which does not just configure, for example: “rewrite” or “fastcgi_pass”
  • try_files directive.

Normal directives are by far the most common one and follows the default inheritance model without any surprises. Lets have a look at an example configuration that show cases the behaviour.

server {
    root /home/user/public_html;

    location /app {
        root /usr/share; # This results in /usr/share/app
                         # Full URI is ALWAYS appended.
    }

    location /app2 {
        // Server context root applies here.
    }
}

Array directives are a lot like normal directives in the sense that they follow the standard inheritance model of always inheriting downwards and replacing any directives specified in a higher context. What might be confusing about these is to assume that you add to the array. The behaviour of an array directive is that if you define multiple directives in the same context you will add to the values, but if you define multiple directives in different contexts then the lower context will replace the higher context ones. This means that you need to sometimes double define a value if you want it present in multiple context. An example of such a scenario.

server {
    access_log /var/log/nginx/access.log;
    include fastcgi.conf;

    location ~ ^/calendar/.+\.php$ {
        access_log /var/log/nginx/php-requests.log; # If this executes then server context one never does.

        fastcgi_param ENV debug; # This *overwrites* the higher context array.
        include fastcgi.conf     # Therefore we include it in *this* context again.
    }
}

Action directives are where it starts to get interesting. They are confined to one context and will never inherit downwards, they can however be specified in multiple contexts and in some cases will be executed for each context. The rewrite directive is an action directive that is allowed in server and location context where both contexts might be executed.

server {
    rewrite ^/booking(.*) /calendar$1 permanent; # Always executes.

    location /calendar {
        rewrite ^ /index.php; # Can execute in addition to and does not replace server context rewrites.
    }
}

Naturally, it’s not quite that simple. Within locations there are three possible contexts, a nested location, an if and limit_except. The behaviour of a directive is actually entirely up to the module that defines it. All the normal and array directives will inherit properly if they are allowed in that context. For action directives the story is a bit different. Generally they will not inherit into a nested location but it ultimately depends on how the module wants it to be and it can differ on a directive by directive basis. The nginx documentation is not of use here either so you’ll have to just try it and see if nginx complains. For good measure, lets have an example of the most common behaviour and how it affects rewrite :

server {
    location /calendar {
        rewrite ^ /static.php; # Executes unless inner location matches.

        location ~ \.php$ {
            fastcgi_pass backend; # Outer location context rewrite is not executed.	
        }
    }
}

The try_files directive is mostly like every other action directive mentioned above, the difference is that if placed in server context nginx actually creates a pseudo-location that is the least specific location possible. That means if a request matches a defined location the try_files directive will not be executed. This means that if you have location / defined then you have a location that matches every possible request and as such try_files will never actually execution. Therefore always place try_files in location context instead of server context if at all possible.

server {
    try_files $uri /index.php; # This never executes.

    location / {
        # Whatever here, or empty.
    }

    location ~ \.php$ {
        # If this location executes then try_files still does not execute.
        # Even if location / did not exist.
    }
}

Related Posts

14 Comments. Leave new

  • […] of which the hierarchy goes like this: http -> server -> location. (I have since gone into more details in a new blog post)Furthermore there are two special locations, an event block and the root which the event block and […]

    Reply
  • so in the last example would it be appropriate to do this?

    server {

    location / {
    try_files $uri /index.php;
    }

    location ~ \.php$ {
    # etc
    }
    }

    Reply
    • Yes that is by far the most common use case for try_files.

      Reply
      • What if I use root and try_files inside a single location block? Will the $uri be first checked in the root location and only if it is not found go to the try_files directive?

        Reply
        • try_files will execute first, it will just use your newly defined root as the root. If you want $uri tried first you’d have to do

          root /my/path;
          try_files $uri foo bar;

          and then it’d try /my/path$uri first.

          Reply
  • Great post! I have something of a love/hate relationship as I feel that I’m continually getting bitten by something that I thought I previously understood; this shows I still have a lot to learn about nginx.

    I’m currently trying to get fastcgi_cache and proxy_cache setups working and it’s been a real struggle thus far. nginx is fast, but the easy configuration it’s purported to have, well, I don’t buy that.

    Hopefully with time I’ll come to see things differently.

    Reply
    • The easy configuration is really in comparison to other webservers such as Apache. There you might find configuration directives in multiple different places with no specific grouping, meaning you’d have to look all over to catch everything. There’s definitely a learning curve for Nginx configuration, no doubt about that at all, but once you get used to it there are few surprises about what goes on because it’s all just right there in one central place.

      Reply
  • Reply
  • We have a server which will host multiple HTML apps from other developers which could need different location blocks with their own try_files directives. We would like to avoid modifying the primary conf file for each app.

    Is there a way the location blocks can be split into different files and processed. The server and root would remain the same.

    Reply
  • […] of how array directives inherit and interact the people using the old configuration style made it impossible to include the line in […]

    Reply
  • […] the more difficult issues not just related to syntax. Don’t skip basic nginx syntax or how a nginx request flows. Once you understand these concepts the non-error issues become far more tangible to work […]

    Reply
  • Codename: Steeve Knight
    May 5, 2015 15:01

    I recently ran into a gotcha within a complex configuration suite where a test request was not yet configured, but resolved to a mysterious location.
    Therein I was hoping to find here detail on how nginx resolves requests across its configured servers.

    Scenario:
    https://subB.mysite.net (requested, not yet configured 443 => subB.mysite.net (nor .mysite.net)
    https://subA.mysite.net (configured 443 => subA.mysite.net, not default_server)
    There are other 443 servers configured – non being *.?mysite.net
    80 => .mysite.net is configured

    Result:
    The request to https://subB.mysite.net “appears” to serve https://subA.mysite.net
    It is as if nginx finds a closest match?
    Note that no 404 was thrown.

    Reply
    • Yes this is not entirely intuitive. Nginx will always choose a server block if there is a valid one.

      Nginx server block works like this:

      Is there a server block listening on this ip:port combination with a matching server_name directive? If yes choose that.
      Is there a server block listening on this ip:port combibation with a default_server flag? If yes choose that.
      Is there a server block listening on this ip:port combination? If yes choose the first one defined.
      If no match yet refuse the connection.

      So that means even if you do not have a hostname configured in nginx, so long as there is a server block listening on the right ip:port combination then nginx will respond. Often times with a seemingly arbitrary server block as config files are usually included without sorting the files alphabetically so the first one defined could be in the file momandpop.com.conf.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.