Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx not setting expires headers on Rails static assets

I can't seem to get nginx to set expires headers on my static assets in my Rails app.

My app is deployed using Phusion Passenger & nginx.

Below is the related section of my nginx config file

server {
        listen  80;
        server_name my.domain.tld;
        root /home/deploy/my.domain.tld/current/public;
        passenger_enabled on;
        access_log off;

        location ~* \.(ico|css|js|gif|jp?g|png)\?[0-9]+$ {
                expires max;
                break;
        }

        if (-f $document_root/system/maintenance.html) {
                rewrite ^(.*)$ /system/maintenance.html break;
        }
}

I'm not sure why its not setting expires headers on my static assets ( e.g. /images/foo.png?123456 )

I'm not sure if it has something to do with passenger or if my location regexp just isnt catching it

like image 812
cpjolicoeur Avatar asked May 16 '09 20:05

cpjolicoeur


3 Answers

Just wanted to point out that making the timestamp optional is a bad idea – if it's not included, then setting expires max is wrong as there would be no way of refreshing the file.

Also, the location directive in Nginx can't see the query string, so the solution posted here never matches the 'optional' timestamp.

A proper solution (ie one that sends the maximum expires only when the file was requested with a timestamp) would be:

location ~* \.(js|css|png|jpg)$ {
  if ($query_string ~ "^[0-9]+$") {
    expires max;
    break;
  }
}

If the timestamp is not specified, then you rely on Last-Modified and ETag, which are handled automatically by Nginx.

like image 94
djanowski Avatar answered Nov 08 '22 17:11

djanowski


So I ended up finding the solution. My regexp was a bit off, as I wasn't taking into account the possibility that the ?timestamp didn't exist.

This regexp worked for me.

location ~* \.(ico|css|js|gif|jp?g|png)(\?[0-9]+)?$ {
like image 23
cpjolicoeur Avatar answered Nov 08 '22 18:11

cpjolicoeur


there is no need to use "break" directive, but access_log off; will be useful:

  location ~* \.(png|gif|jpg|jpeg|css|js|swf|ico)(\?[0-9]+)?$ {
      access_log off;
      expires max;
      add_header Cache-Control public;
  }

you can see full config file at github: https://gist.github.com/711913

like image 41
Anatoly Avatar answered Nov 08 '22 16:11

Anatoly