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.
Have you tried Cache-Control flags in your nginx configuration ?
Sample configuration:
I think you are looking for this particular configuration snippet
I too use the "environment variable trick" to do this in Apache and was looking for the equivalent method in nginx. It's been a few years since this question was first asked, so things may have changed since then, but I did find a way to set a default lifetime for redirects in nginx 1.14.
In a
server
block, you can effectively set new defaultCache-Control
andExpires
header values for all 301 redirects by using a map variable to set the value of theexpires
directive based on the return status code ($status
). If desired, this new default can be overridden in more specificlocation
blocks where necessary. As an added bonus, you don't have to repeatedly specify an environment variable with every redirect like you do in Apache.Here's an example that illustrates this, where all HTTP requests are upgraded to HTTPS using "permanent" 301 redirects that only last for an hour. An exception has been made for URI's prefixed with
/override
, where the 301 is left to indeed be permanent.This gives the expected header values: