Process data BEFORE a 301 Redirect?
So, I've been working on a PHP link shortener (I know, just what the wor开发者_Python百科ld needs). Basically when the page loads, php determines where it needs to go and sends a 301 Header to redirect the browser, like so...
Header( "HTTP/1.1 301 Moved Permanently" );
header("Location: http://newsite.com";
Now, I'm trying to add some tracking to my redirects and insert some custom analytics data into a MySQL table before the redirect happen. It works perfectly if I don't specify the a redirect type and just use:
header("Location: http://newsite.com";
But, of course as soon as you add in the 301 header, nothing else gets processed. Actually, on the first request, it sends the data to MySQL, but on any subsequent requests there's no communication with the database.
I assume it's a browser caching issue, once it's seen the 301 it decides they're no reason to parse anything on future requests. But, does anyone know if there's any way to get around this?
I'd really like to keep it as a 301 for SEO purposes (I believe if you don't specify it sends a 404 by default?).
I thought about using .htaccess to prepend a file to the page that will do the MySQL work, but with the 301, wouldn't that just get ignored as well?
Anyway, I'm not sure if there's any solution other than using a different type of redirect, but I'm ready to give up just yet. So, any suggestions would be much appreciated. Thanks!
Try adding the following before the first header statement; this should prevent caching in typical pages, but I'm not sure if it works for redirects:
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Thu, 1 Jan 1970 00:00:00 GMT");
The explanation is in the description of the 301 code: "Moved Permanently" You're specifically telling the browser that the new page is a permanent new location, and therefore there's no reason for it to ever visit the old URL again.
Instead, use a 303 See Other status. This has roughly the same meaning (in that it redirects the visitor elsewhere), but it "must not" be cached.
You should use the default 302 redirect, which is a temporary redirect and will not be cached.
301 is the permanent redirect and most browser will cache it.
精彩评论