一个URL:两个不同的重定向


One URL: Two Different Redirects

我有一个URL,曾经处理过GETPOST请求。我希望它现在只处理POST请求,并为其他请求重定向。基于这个问题,看来我应该在处理POST请求后使用303,并为其他请求使用301

我的代码流看起来像这样:

if ('POST' === filter_input(INPUT_SERVER, 'REQUEST_METHOD')) {
    // process post request
    // set http status code
    header('HTTP/1.1 303 See Other');
} else {
    // set http status code
    header('HTTP/1.1 301 Moved Permanently');
}
header('Location: /newurl.php');

这是重定向代码的正确用户吗?我想确保301不会被浏览器缓存时,POST请求。

对于303重定向,您必须指定重定向URI:

<?php
header('HTTP/1.1 303 See Other');
header('location: http://www.example.com/some-url/');

作为缓存301响应的解决方法,您可以将过期日期设置在过去。这种方式鼓励客户端立即将响应标记为过期:

<?php
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Expires: Sat, 1 Feb 1997 06:00:00 GMT');

任何遵守RFC 2616的客户端都不应该缓存303响应:

不能缓存303响应,但要缓存第二个响应(重定向)请求可能是可缓存的。

考虑到上述情况,您可以将初始代码片段更改为如下内容:
if ('POST' === filter_input(INPUT_SERVER, 'REQUEST_METHOD')) {
    // process post request
    // set http status code
    header('HTTP/1.1 303 See Other');
    header('Location: http://www.example.com/newurl.php'); // FULL URI HERE
    exit;
}
// set http status code
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"); // Date in the past
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://www.example.com/other-page.php');

但是,在您的情况下,307重定向应该更合适。虽然307是一个临时重定向,你总是会重定向任何请求,而不是POST,你可以改变这种行为在未来,因为根据RFC"由于重定向可能会偶尔改变,客户端应该继续使用请求uri为未来的请求"。第二个优点是:"这个响应只有在Cache-Control或Expires报头字段指定时才可缓存。"

请求的资源暂时驻留在不同的URI下。
由于重定向有时会改变,客户端应该
继续为将来的请求使用Request-URI。这个响应
只有在缓存控制或过期头
指定时才可缓存场。

参见RFC 2616第10.3.8节

你的重定向应该是

header('Location: http://www.example.com/newurl.php',true,301);

用于301代码,与303类似(因此不需要最后一个Location标头)。