Jos*_*ber 5 php redirect header laravel
我正在使用Redirect
该类将未登录的用户发送到登录页面,其中包含401状态代码:
return Redirect::to('login', 401);
Run Code Online (Sandbox Code Playgroud)
这将发送正确的位置标头,但状态代码设置为302.
我一直跟踪它到基Response
类
laravel /供应商/ Symfony的/组件/ HttpFoundation/Response.php
它正在呼唤:
$this->setStatusCode($status);
Run Code Online (Sandbox Code Playgroud)
使用正确的401代码.
我也试过转储对象:
var_dump( Redirect::to('login', 401)->foundation );
Run Code Online (Sandbox Code Playgroud)
我可以看到受保护的statusCode
属性被正确设置为401.
仍然,生成的响应的HTTP状态代码设置为302.
是什么赋予了?我用错了吗?
PS我也在Laravel的论坛上发布了这个,但无济于事.
这不是因为 laravel,你可以用(windows 中的 php 5.4)重现这个:
<?php
header("HTTP/1.1 401 Unauthorized");
header("Location: http://www.google.com");
Run Code Online (Sandbox Code Playgroud)
看来 php 将其设置为 302:
$ php-cgi "test.php"
Status: 302 Moved Temporarily
Location: http://www.google.com
Content-type: text/html; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)
在PHP源代码main/SAPI.C中:
} else if (!STRCASECMP(header_line, "Location")) {
if ((SG(sapi_headers).http_response_code < 300 ||
SG(sapi_headers).http_response_code > 307) &&
SG(sapi_headers).http_response_code != 201) {
/* Return a Found Redirect if one is not already specified */
if (http_response_code) { /* user specified redirect code */
sapi_update_response_code(http_response_code TSRMLS_CC);
} else if (SG(request_info).proto_num > 1000 &&
SG(request_info).request_method &&
strcmp(SG(request_info).request_method, "HEAD") &&
strcmp(SG(request_info).request_method, "GET")) {
sapi_update_response_code(303 TSRMLS_CC);
} else {
sapi_update_response_code(302 TSRMLS_CC);
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,当你使用 时header()
,"Location"
http状态码被修改为302
如果你以相反的方式做,你可以让它工作:
<?php
header("Location: http://www.google.com");
header("HTTP/1.1 401 Unauthorized");
Run Code Online (Sandbox Code Playgroud)
这将给出:
$ php-cgi "test.php"
Status: 401 Unauthorized
Location: http://www.google.com
Content-type: text/html; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)
但是laravel在设置status之后才设置位置,所以status无论如何都被设置回302。但这是一个有争议的问题,即使您成功使用位置标头将状态设置为 401,浏览器也不会遵循重定向。