107

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'?

139

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";
}
| improve this answer | |
  • 8
    All my static files were not found after adding that. – Jürgen Paul May 31 '12 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? – J. M. Becker May 31 '12 at 17:26
  • 29
    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 '14 at 23:36
  • 1
    I personally appreciate clarifications, especially for future searchers because they often show up long after the original post. +1 :P – J. M. Becker Jul 21 '14 at 18:14
  • using this totally messes up my wordpress website. css and images are not show. is there any other conflict somewhere? – user1641443 Apr 27 '15 at 10:57
22
server {
    ...

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

The location directive

The expires directive

| improve this answer | |
20

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;
}
| improve this answer | |
  • 2
    +1 for making this a reusable .conf. The appropriate folder in nginx/1.14.0 (Ubuntu) seems to be /etc/nginx/snippets/. – Jan Werkhoven Oct 26 '18 at 9:57
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;
}
| improve this answer | |
  • 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 – Dave Cheney Jun 10 '09 at 10:47
  • You are right. Forgot to clean this up. Edited to reflect this. – Jauder Ho Jun 11 '09 at 1:02
8

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.

| improve this answer | |
  • Note that if $sent_http_content_type is "text/css;charset=UTF-8" the above expression will fail. – pachanka Jun 6 '18 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. – leetNightshade Sep 9 at 19:46
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.

| improve this answer | |
  • 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 '19 at 15:16
-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

| improve this answer | |
  • 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 '17 at 17:21
  • @Unkwntech I cannot agree more, I just updated my answer :) – Mohamed Kawsara Jul 10 at 6:29
  • The map block is better added in a conf file, then included in site configs. – leetNightshade Sep 9 at 19:45
  • Good to know, I would appreciate it if you can edit my answer or show me how to do so – Mohamed Kawsara Sep 10 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.