General Rules to Follow Regarding Contexts
Many directives are valid in more than one context. For instance, there are quite a few directives that can be placed in the http
, server
, or location
context.
As a general rule, it is usually best to declare directives in the highest context to which they are applicable, and overriding them in lower contexts as necessary. This is possible because of the inheritance model that Nginx implements.
Declaring at a high level allows you to avoid unnecessary repetition between sibling contexts:
http {
server {
location / {
root /var/www/html;
. . .
}
location /another {
root /var/www/html;
. . .
}
}
}
You could move the root
out to the server
block, or even to the http
block:
http {
root /var/www/html;
server {
location / {
. . .
}
location /another {
. . .
}
}
}
Most of the time, the server
level will be most appropriate, but declaring at the higher level has its advantages. This not only allows you to set the directive in fewer places, it also allows you to cascade the default value down to all of the child elements, preventing situations where you run into an error by forgetting a directive at a lower level.