2

I wrote a little php script that reads and compresses css and javascript files. I used a rewrite to automatically redirect all resources to that script. The rule looks like this:

rewrite ^(/.*\.(css|js))$ /compress.php?file=$1&type=$2;

However this somehow disables these settings:

location ~* \.(css|js|gif|jpe?g|png|ico)$ {
  expires 168h;
  add_header Pragma public;
  add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

How do I get Nginx to still use these settings?

1 Answer 1

2

You can try to create a separate block for the css / js files, and include the rewrite directive inside that directive, like this:

location ~* (?<filename>.+\.(?<type>css|js))$ {
    expires 168h;
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    rewrite ^ /compress.php?file=$filename&type=$type;
}

Here I use regex captures on the location directive, and capture to named variables. It is just a matter of taste how you do the captures though.

And then reduce the other block to:

location ~* \.(?:gif|jpe?g|png|ico)$ {

I use ?: prefix here to indicate that we don't need to make any regex captures.

If that doesn't work, then you have to set the cache headers inside your compress.php script with header() function.

1
  • Ok. It is still not working. I guess I have to stick defining the headers in php...
    – BrainStone
    Aug 17, 2014 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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