Sub topic 14
Reusing settings with include snippets
This chapter assumes you can edit files under /etc/nginx with sudo. It also assumes you have two or more server blocks working, and that you know the nginx -t and reload workflow from earlier chapters. After many sites accumulate, the same lines show up in every server block: TLS settings, proxy headers, security headers, and cache rules. The include directive lets you keep each group of lines in one file and pull it into every site that needs it.
How include works
include reads another file, or a set of files matched by a glob, and treats its contents as if you had typed them at that spot. It is a textual substitution done when Nginx parses the configuration. It is not a function call, and it has no parameters.
include /etc/nginx/snippets/security-headers.conf;
include /etc/nginx/conf.d/*.conf;Key facts about include:
- It is allowed in any context. You can put it in
http,server,location, and so on. - A relative path is resolved against the directory that holds the main
nginx.conf, normally/etc/nginx. - A glob that matches no files is fine. A path with no wildcard that does not exist is an error.
- The included text must be valid for the context where it lands. A
server_nameline included inside alocationblock failsnginx -t.
The main file already uses this. On Debian and Ubuntu, nginx.conf contains lines like these inside http:
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;Each site file you enabled earlier is itself an include. Snippets use the same mechanism one level further down.
Where snippets live
Debian and Ubuntu packages create /etc/nginx/snippets/. It is only a convention. Nginx never reads that directory on its own, and a file there takes effect only when something includes it. If your distribution has no such directory, create it.
Do not put snippets in conf.d/ or sites-enabled/ unless they are complete, valid pieces for the http context. Those directories are included automatically with a *.conf or * glob, so a half-finished snippet placed there will be loaded in the wrong context and break the reload.
| Location | Loaded automatically? | Typical content |
|---|---|---|
| `/etc/nginx/conf.d/*.conf` | Yes, in `http` | Shared `http`-level settings, upstreams, `map` blocks |
| `/etc/nginx/sites-enabled/*` | Yes, in `http` | One complete site (server blocks) per file |
| `/etc/nginx/snippets/*.conf` | No, only when included | Fragments for `server` or `location` context |
A first snippet: security headers
Create the file:
sudo mkdir -p /etc/nginx/snippets
sudo tee /etc/nginx/snippets/security-headers.conf > /dev/null <<'EOF'
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
EOFInclude it from a site:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
include snippets/security-headers.conf;
location / {
try_files $uri $uri/ =404;
}
}The path snippets/security-headers.conf is relative to /etc/nginx. Now a change to the header policy is one edit, and every site that includes the file picks it up on the next reload.
Snippet for reverse proxy headers
The proxy header lines from the earlier reverse proxy chapter are a good candidate. They are identical for most applications.
sudo tee /etc/nginx/snippets/proxy-headers.conf > /dev/null <<'EOF'
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
EOFThis snippet is meant for location context, because proxy_pass lives there. The site file shrinks:
server {
listen 80;
listen [::]:80;
server_name app.example.net;
access_log /var/log/nginx/app.example.net.access.log;
error_log /var/log/nginx/app.example.net.error.log;
location / {
proxy_pass http://127.0.0.1:3000;
include snippets/proxy-headers.conf;
}
}Variables such as $host are expanded at request time, not when the snippet is read. That is why one snippet works correctly for every site that includes it.
Snippet for TLS settings
Settings that you want identical across all HTTPS sites also fit well. Keep the per-site parts, which are the certificate paths and server_name, in the site file.
sudo tee /etc/nginx/snippets/tls-common.conf > /dev/null <<'EOF'
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
EOFserver {
listen 443 ssl;
listen [::]:443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include snippets/tls-common.conf;
root /var/www/example.com/html;
index index.html;
}The shared:SSL:10m cache is a named memory zone. Every ssl_session_cache line that uses the name SSL with the same size shares that one zone. Repeating the same line in several server blocks is therefore fine. Giving the same zone name two different sizes is an error.
The inheritance trap with add_header
Snippets make one Nginx rule easy to trip on. Directives such as add_header, proxy_set_header, and proxy_hide_header are inherited from an outer context only if the inner context defines none of its own. As soon as a location contains a single add_header, it no longer inherits any add_header lines from the enclosing server.
server {
listen 80;
server_name example.com;
root /var/www/example.com/html;
include snippets/security-headers.conf;
location /downloads/ {
add_header Content-Disposition "attachment";
}
}Requests to /downloads/ get only Content-Disposition. The three security headers from the server-level include are lost there. The fix is to include the snippet again inside that location:
location /downloads/ {
include snippets/security-headers.conf;
add_header Content-Disposition "attachment";
}The same rule applies to proxy_set_header. If a location adds its own proxy_set_header, include proxy-headers.conf there as well.
Designing snippets that stay reusable
A few habits keep snippets from turning into a second tangle.
- Give each snippet one job and name it for that job:
proxy-headers.conf, notcommon.conf. - Put the intended context in a comment at the top of the file, so nobody includes a
locationfragment inhttp. - Keep site-specific values out. Host names, certificate paths, upstream ports, and log paths belong in the site file.
- Avoid defining the same single-value directive in a snippet and again in the including block. Directives like
rootorindexmay not be repeated in one context, and a duplicate gives"root" directive is duplicateat test time. - Do not nest snippets deeply. One level of include from a site file is easy to follow. Three levels make the effective configuration hard to read.
Here is a snippet with a context comment:
# Context: server or location
# Purpose: deny access to hidden files such as .git and .env
location ~ /\.(?!well-known) {
deny all;
}Because this snippet contains a location, it can only be included at server level. Including it inside another location is legal syntax in some cases, but it nests the match and rarely does what you want.
Seeing the effective configuration
When includes pile up, you need to see what Nginx actually loaded. Print the fully expanded configuration with:
sudo nginx -T | lessThe uppercase -T tests the configuration and then dumps it. Each file is introduced by a comment line such as # configuration file /etc/nginx/snippets/proxy-headers.conf:, so you can see which snippet supplied which line. This output may contain private paths and key file locations, so redact it before pasting it into a public bug report.
To check that a snippet works, apply the usual loop:
sudo nginx -t && sudo systemctl reload nginx
curl -I --resolve example.com:80:127.0.0.1 http://example.com/The -I option prints only the response headers. You should see the three headers from the security snippet.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `nginx -t` reports `open() "/etc/nginx/snippets/x.conf" failed (2: No such file or directory)` | Typo in the include path, or the file was never created | Check the name. Remember that relative paths start at `/etc/nginx`. |
| `"location" directive is not allowed here` | A snippet containing `location` was included inside `http` or inside a context that forbids it | Move the include to `server` level. |
| `"server_name" directive is not allowed here` | A server-level snippet was included inside `location` | Include it in the `server` block. |
| Headers present on `/` but missing on another path | A `location` with its own `add_header` stopped inheritance | Include the snippet inside that location too. |
| `"root" directive is duplicate` | Both the snippet and the site file set `root` in the same block | Keep `root` in one place only. |
| A half-written snippet breaks every reload | The file sits in `conf.d/` or `sites-enabled/` and is loaded automatically | Move it to `snippets/`. |
Chapter recap in practice
Take a site you already have, and try this sequence:
- Move the proxy header lines into
/etc/nginx/snippets/proxy-headers.conf. - Replace them in the site with one
includeline. - Run
sudo nginx -t, then reload. - Run
sudo nginx -T | grep -n proxy_set_headerand confirm the four lines still appear under the right location.
The behavior of the site should not change at all. A refactor into snippets is correct when the output of nginx -T, apart from file markers, describes the same effective rules as before.
Exercise
A server block includes snippets/security-headers.conf at server level. A request to / returns the security headers, but a request to /downloads/ does not. That location contains its own add_header line. Why are the headers missing, and how do you fix it?
Show answer
addheader is inherited from the enclosing level only when the inner level defines no addheader of its own. The /downloads/ location defines one, so it drops all server-level add_header lines. Fix it by adding include snippets/security-headers.conf; inside the /downloads/ location, then run sudo nginx -t and reload.
Exercise
You put a file called proxy-headers.conf, containing only proxysetheader lines, in /etc/nginx/conf.d/. What happens at the next nginx -t, and where should the file live instead?
Show answer
The default nginx.conf includes conf.d/*.conf in the http context, where proxysetheader lines are valid syntax, so the test may pass. The lines would then apply to every site as http-level defaults, which is not what you intended, and any location that sets its own proxysetheader silently ignores them. Place the file in /etc/nginx/snippets/ and include it only in the locations that proxy.