Cache-control for permanent 301 redirects nginx

Posted by gansbrest on Server Fault See other posts from Server Fault or by gansbrest
Published on 2012-05-30T16:25:23Z Indexed on 2012/05/30 16:44 UTC
Read the original article Hit count: 311

Filed under:
|
|

I was wondering if there is a way to control lifetime of the redirects in Nginx?

We would liek to cache 301 redirects in CDN for specific amount of time, let say 20 minutes and the CDN is controlled by the standard caching headers. By default there is no Cache-control or Expires directives with the Nginx redirect. That could cause the redirect to be cached for a really long time. By having specific redirect lifetime the system could have a chance to correct itself, knowing that even "permanent" redirect change from time to time..

The other thing is that those redirects are included from the Server block, which according the nginx specification should be evaluated before locations.

I tried to add add_header Cache-Control "max-age=1200, public"; to the bottom of the redirects file, but the problem is that Cache-control gets added twice - first comes let say from the backend script and the other one added by the add_header directive..

In Apache there is the environment variable trick to control headers for rewrites:

RewriteRule /taxonomy/term/(\d+)/feed /taxonomy/term/$1 [R=301,E=expire:1] Header always set Cache-Control "store, max-age=1200" env=expire

But I'm not sure how to accomplish this in Nginx.

© Server Fault or respective owner

Related posts about nginx

Related posts about redirect