How to enable default Nginx object caching to all sites at once?

user9303970 asked:

Say I have 20 sites and I wish to automate the process of pasting 1X1 nginx.conf caching directives and 1X20 caching directives per 20 different virtual hosts I have?

Also, my virtual hosts have already been modified by Certbot and became a bit messy (Certbot 0.21.1-1+ubuntu16.04.1+certbot+0.2 adds many spaces and comments), so I’m now even less sure how to efficiently enable Nginx object caching for all my sites.

How would you do so efficiently?

My answer:

Use includes.

Here’s a typical configuration from one of my web sites:

server {

        root /srv/www/;

        access_log /var/log/nginx/ nginx;
        access_log /var/log/nginx/cache.log cache;
        error_log /var/log/nginx/;

        ssl_certificate /etc/letsencrypt/live/;
        ssl_certificate_key /etc/letsencrypt/live/;
        ssl_trusted_certificate /etc/letsencrypt/live/;

        include includes/listen-443;
        include includes/cloudflare;
        include includes/letsencrypt;
        include includes/ssl;
        include includes/ssl_stapling;
        include includes/hsts;
        include includes/csp_wordpress;
        include includes/favicon;
        include includes/wordpress;
        include includes/php;
        include /srv/www/;

        location ~ /\.(ht|git) {
                deny all;

The content of /etc/nginx/includes/letsencrypt, for example, is:

location /.well-known/acme-challenge/ {
    root /var/www;
    try_files $uri =404;

While /etc/nginx/includes/listen-443 consists of:

listen 443 ssl http2;
listen [::]:443 ssl http2;

In this way you can pull out anything that is repeated among your server blocks, and include it wherever you need to do so.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.