suther
suther

Reputation: 13628

How can I set Cache-Control globally in NGINX

I want to setup a general cache-control for all NGINX-Sites. Here is an example of it:

location ~* \.(?:ico|gif|jpe?g|png|svg?z)$ {
        expires 1y;
        add_header Pragma public;
        add_header Cache-Control public;
}

If I try to add this "location" setting to /etc/nginx/nginx.conf I got an error, that I can't set it here.

So is there a way to set this cache handling for all sites in nginx by default, without the need to edit each single host in /sites_available/ ?

Upvotes: 0

Views: 1925

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15687

No, you can't use location directive in contexts other than server or another location. However you can use the following workaround (this one can be added to the http context):

map $cache $public {
    1       public;
}

map $cache $expires {
    1       1y;
    default off; # or some other default value
}

map $uri $cache {
    ~*\.(?:ico|gif|jpe?g|png|svg?z)$    1;
}

expires $expires;
add_header Pragma $public;
add_header Cache-Control $public;

nginx won't add the header at all (or modify an existing header) if the value calculated via the map expression will be an empty string. But be aware of this documentation excerpt:

There could be several add_header directives. These directives are inherited from the previous configuration level if and only if there are no add_header directives defined on the current level.

Upvotes: 1

Related Questions