0

This is my Nginx default conf (sites-available/default), which I use as base conf for all apps:

server {
    # listen, root, index, server_name, locations;
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;
    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

Each app also has an individual Nginx conf (sites-available/${domain}.con):

server {
    root ${drt}/${domain}/;
    server_name ${domain} www.${domain};
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ { expires 365d; }
}

There is a small duplication here: If I have say 10 apps on that server, I get a duplication of *10 lines of the cache expiration directive:

location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ { expires 365d; }

Instead having ten location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ { expires 365d; } entries, is it logical / safe to delete all of these entries and keep just one such line in the default conf? These are personal apps and I personally see no problem giving them all the same caching directives, I just want to reduce redundancy.

Arcticooling
  • 119
  • 1
  • 14

1 Answers1

1

That won't work, a request is serviced by a single server block unless explicity forwarded to another.

The way to do this is with includes. For example

# File site-a.conf
server {
  root /var/www/site1;
  server_name sub1.example.com;

  include /etc/nginx/fragments/jpeg-expires.conf;
}

# File site-b.conf
server {
  root /var/www/site2;
  server_name sub2.example.com;

  include /etc/nginx/fragments/jpeg-expires.conf;
}

# file /etc/nginx/fragments/jpeg-expires.conf
location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
  expires 365d; 
}

You can define as many files to include as you like, and include them anywhere. Beware of recursion.

Tim
  • 30,383
  • 6
  • 47
  • 77