Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding 301 redirect caching

This is a follow up question to Using 301/303/307 redirects for dynamic short urls, where I try to determine the best method for implementing short url redirection when the destination url will change on a frequent basis.

While it seems that 301 and 307 redirects both perform the same way, the issue that concerns me is 301 redirect caching (as documented here)- is the best way to avoid this to use 307 redirects instead (I'm assuming 307 redirects will never cache?), or to explicitly send a no-cache header ("Cache-Control: no-cache, must-revalidate")?

like image 945
Yarin Avatar asked Jan 26 '12 15:01

Yarin


People also ask

Do 301 redirects get cached?

If you put a 301 redirect into operation, that redirect will be cached in the browser for any visitor's on your site. You can't clear the browser cache for your users, so if you need to change or undo a 301 redirect, the old redirect is still going to be in effect until their cache expires.

How do I remove cached redirects?

Open the Developer Tools Panel by pressing CTRL + Shift + i on Windows or Option + Shift + i on Mac. When you see a developer tools panel open, look the the left of your URL bar to see a refresh icon. Hold the refresh icon for a few seconds until a menu appears. Then click Empty Cache and Hard Reload .


2 Answers

Don't try to avoid 301 caching. If you don't want any user agent to cache your redirect, then simply don't use a 301 redirect. In other words, 301 caching is here to stay, and semantically, it's a permanent redirect, so if you're planning to change the destination URL, 301 is not the right status code to use. On the other hand, 307 responses are not cached by default.

like image 161
Mauricio Scheffer Avatar answered Oct 19 '22 10:10

Mauricio Scheffer


In situations where you want the behaviour that a 301 redirect brings, like the updating of browser bookmarks and the change of URL in google bot, but at the same time want to track the redirects or perform some other kind of functionality you can always add the cache control headers to "no cache"

HTTP/1.0 301 Moved Permanently
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Location: http://example.com

In php it looks like this:

header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Location:'.$url, true, 301);

Related: https://stackoverflow.com/a/19003320/175071

like image 25
Timo Huovinen Avatar answered Oct 19 '22 10:10

Timo Huovinen