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

link|improve this question

62% accept rate
feedback

3 Answers

up vote 3 down vote accepted

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";
}
link|improve this answer
feedback
server {
    ...

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

The location directive

The expires directive

link|improve this answer
feedback

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;
}
link|improve this answer
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
feedback

Your Answer

 
or
required, but never shown

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