301 is a constant redirect, so caching makes sense. If your redirect is not permanent, use 307 (temporary redirect), 302 (found) or 303 (see Others).
See here for relevant use cases.
To clarify the differences between the three:
- 307 is a general temporary redirect when a resource moves. For example, a URL such as
domain.com/news/latest might redirect 307 to the latest news article domain.com/news/article-594873 . Since this temporary redirect may persist for a while (this particular article may be the last for several hours), browsers may cache the redirect. To control the extent to which they are executed, use the cache control headers. - 303 is a redirect that cannot be cached ever. For example, POSTing a new article at
domain.com/news can create a new news article, and a 303 redirect to it is provided by domain.com/news/article-978523 . Since another POST request results in a completely different article being created, it cannot be cached. - 302 is a little weirder, I never used it myself. Apparently, this is more of a substitute for legacy 303, for earlier HTTP version 1.0 clients that do not understand 303.
Since you asked specifically about PHP:
<?php function header_redirect_permanent($url) { header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently', true, 301); header('Location: ' . $url); } function header_no_cache() { 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');
You can also stop agents from caching 301, if necessary, using the above cache control headers, for example:
header_no_cache(); header_redirect_permanent($url);
or just add
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); exit;
Core xii
source share