112

I'm using nginx to server my static content, is there a way that I can set the expires headers for every file that meets a specific rule? For example can I set the expires header for all files that have an extension of '.css'?

8 Answers 8

141

I prefer to do a more complete cache header, in addition to some more file extensions. The '?' prefix is a 'non-capturing' mark, nginx won't create a $1. It helps to reduce unnecessary load.

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}
10
  • 9
    All my static files were not found after adding that. May 31, 2012 at 0:45
  • @JackSpairow: I can't really explain why that happened, as It has always worked for me. Are you running Nginx missing the add_header providing module? This kind of thing really is limited in scope, you sure another deceleration is not a problem in combination? May 31, 2012 at 17:26
  • 30
    Probably another block had definition for the static files with a root set, in that case you should add the directives to that block. (I know this is 2y late, but for future citizens)
    – aularon
    Jul 5, 2014 at 23:36
  • 1
    I personally appreciate clarifications, especially for future searchers because they often show up long after the original post. +1 :P Jul 21, 2014 at 18:14
  • using this totally messes up my wordpress website. css and images are not show. is there any other conflict somewhere? Apr 27, 2015 at 10:57
23
server {
    ...

    location ~* \.css$ {
       expires 30d;
    }
    ...
}

The location directive

The expires directive

22

I don't have enough reputation to comment on why the accepted answer would cause the files to no longer show up, but I figured it out and would like to help out!

Short version:

Make sure you have a root directory specified for your location block on images if you do not have a global one set!

Long version below:


First of all, my method of implementing this solution was really similar to this answer, where you write the rule (as in the accepted answer):

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}

into a file img-cache.conf

and then include that file into your server {...} directive.

My example of somesite.com in my sites-available folder:

 #Image Caching
 include /etc/nginx/conf/img-cache.conf;

That way you can add the image caching location block to multiple sites you might be running.


Second of all, I have a situation where my /var/www/ contains two folders that I allow as public_html - secure and training, so I have to make specific location blocks in my site's server directive singling out these folders.

As such, I do not have a global root directory set.

So when you make your image location blocks, you may not be providing them with a root directory from which to look for the images in!

My solution was then to:

location ~ ^/training.+\.(?:ico|css|js|gif|jpe?g|png)$ {
        root /var/www/;
        expires 7d;
        add_header Pragma public;
        add_header Cache-Control "public";
        try_files $uri 404;
}

location ~ ^/.+\.(?:ico|css|js|gif|jpe?g|png)$ {
        root /var/www/secure;
        expires 7d;
        add_header Pragma public;
        add_header Cache-Control "public";
        try_files $uri 404;
}
1
  • 2
    +1 for making this a reusable .conf. The appropriate folder in nginx/1.14.0 (Ubuntu) seems to be /etc/nginx/snippets/. Oct 26, 2018 at 9:57
10

All the aforementioned solutions will deny the possibility to have different aliases for different paths. Also for the sake of having all your different cache expirations in one place you should use nginx map in the following way.

...

# Expires mappings
map $sent_http_content_type $expires {
    default                    off;
    text/html                  epoch;
    text/css                   max;
    application/javascript     7d;
    ~image/                    max;
}

...

server {
   listen ...;

   expires $expires;
   location /assets/ {
      # It is now possible to serve some resources from different path
      alias /var/www/my_other_path/
   }

   # and have them all have same expirations
   location / {
       try_files $uri $uri/ /index.html;
   }
...
}

Off disables caching, epoch (for unix epoch) results in resource always being refetched, max sets the date to browser max value.

The ~image/ matches any image types.

More about nginx maps at http://nginx.org/en/docs/http/ngx_http_map_module.html.

2
  • 1
    Note that if $sent_http_content_type is "text/css;charset=UTF-8" the above expression will fail.
    – pachanka
    Jun 6, 2018 at 3:56
  • For convenience above map block could be included in a shared conf file, then included in all the site configs you have. Sep 9, 2020 at 19:46
9

You can also set the expires to maximum. Here is the directive I use for css and js.

# Set css and js to expire in a very long time
location ~* ^.+\.(css|js)$ {
    access_log off;
    expires max;
}
2
  • 1
    I would use the root directive only in the server {} block, when using it in sub locations it leads to unexpected consequences. You don't need the break; either, as you're not in an if {} block Jun 10, 2009 at 10:47
  • You are right. Forgot to clean this up. Edited to reflect this.
    – Jauder Ho
    Jun 11, 2009 at 1:02
2

If you have one place that is home to all your static files, something like this will do...

 location /static {
            your/location/to/static/files/static;
            expires 30d;
            add_header Cache-Control "public";
    }

The accepted answer caused nginx to not find any of my static files. Not really sure why, but this is a simple alternative.

1
  • I voted for this one but make sure you add the /static folder (whatever you set in location) at the end of the alias (right after .../files in the example).
    – Miro J.
    Jun 7, 2019 at 15:16
0

Most of the answers on this page are extremely outdated and/or convoluted...

For starters, the Expires header is not a good option these days, nor is the Pragma header... ideally, you should disable both of these headers in your Nginx configuration.

more_clear_headers "Pragma Expires";

It's much cleaner to set a single Cache-Control header on your static assets location block:

location ~* \.(atom|bmp|bz2|css|doc|docx|eot|gif|gz|ico|jpeg|jpg|js|mid|midi|mp4|ogg|ogv|otf|png|ppt|rar|rss|rtf|svg|svgz|tar|tgz|ttc|ttf|wav|webp|woff|woff2|xls|zip)$ {
    add_header Cache-Control "public, max-age=691200";
}

Remember that for Nginx, if you use the expires directive such as expires max this is NOT just setting an HTTP Expires header, it's also setting a Cache-Control header too, so it can get very messy rather quickly.

TLDR just use Cache-Control on your static files so that CDNs like Cloudflare can cache them at the edge and/or browsers can cache them for a while.

And I recommend NOT using any cache headers for your page/HTML content on dynamic sites like WordPress because it will only lead to conflicts and confusion... if you really want to, you can just use an etag for your pages, but I personally don't and think those make more sense when using aggressive output caches like Varnish or Litespeed's LS Cache.

The approaches above are what we use in SlickStack and it works fantastic for performance and stability, while guarding against e.g. WordPress plugins (or people) messing with your settings.

-1

Step1: Configuring Cache-Control and Expires Headers:

sudo nano /etc/nginx/sites-available/default

Add the following above the server block:

# Expires map
map $sent_http_content_type $expires {
    default                    off;
    text/html                  epoch;
    text/css                   max;
    application/javascript     max;
    ~image/                    max;
}

And this line within server block. expires $expires;

sudo systemctl restart nginx

Source: DigitalOcean

4
  • 1
    Generally, we frown upon linking to articles and not including the content here as well, as links have a tendency to change or expire.
    – Unkwntech
    May 26, 2017 at 17:21
  • @Unkwntech I cannot agree more, I just updated my answer :) Jul 10, 2020 at 6:29
  • The map block is better added in a conf file, then included in site configs. Sep 9, 2020 at 19:45
  • Good to know, I would appreciate it if you can edit my answer or show me how to do so Sep 10, 2020 at 21:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .