Process data BEFORE a 301 Redirect?

女生的网名这么多〃 提交于 2020-01-06 06:54:32

问题


So, I've been working on a PHP link shortener (I know, just what the world 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!


回答1:


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");



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2954799/process-data-before-a-301-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!