Laravel未添加自定义标头

6
使用 Laravel,我正在尝试将自定义标头添加到服务器的所有响应中。
我在 filters.php 中有以下内容:
App::after(function($request, $response)
{
    // security related 
    $response->headers->set('X-Frame-Options','deny'); // Anti clickjacking
    $response->headers->set('X-XSS-Protection', '1; mode=block'); // Anti cross site scripting (XSS)
    $response->headers->set('X-Content-Type-Options', 'nosniff'); // Reduce exposure to drive-by dl attacks
    $response->headers->set('Content-Security-Policy', 'default-src \'self\''); // Reduce risk of XSS, clickjacking, and other stuff
    // Don't cache stuff (we'll be updating the page frequently)
    $response->headers->set('Cache-Control', 'nocache, no-store, max-age=0, must-revalidate');
    $response->headers->set('Pragma', 'no-cache');
    $response->headers->set('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');
    // CRITICAL: do NOT delete
    $response->headers->set('X-Archer', 'DANGER ZONE');
});

当我测试它时,没有新的标头出现:

[tesla | ~] => curl -o/dev/null -s -D - localhost
HTTP/1.1 200 OK
Date: Wed, 10 Dec 2014 23:13:30 GMT
Server: Apache
X-Powered-By: PHP/5.6.2
Content-Length: 974
Content-Type: text/html; charset=UTF-8

[tesla | ~] =>

我的日志文件中没有任何错误或警告。这是怎么回事?


哪个版本的Laravel?在4中,它是header()而不是headers->set()。http://laravel.com/docs/4.2/responses - mopo922
将其放置在 App::after 中会产生一个错误,指出头已经被发送,但将其放置在 App:before 中可以正常工作。我只是希望有一种更 Laravel 的方式来处理它 :) - 735Tesla
@TheShiftExchange 这是《绿箭侠》的一个参考。非常棒的节目,你应该试试看。https://zh.wikipedia.org/wiki/%E7%BB%B4%E5%A4%9A%E5%8A%A0%E5%B0%BC%E4%BA%9A%E6%8A%A2%E5%A3%AB - 735Tesla
哈哈 - 我知道《绿箭侠》 - 我一直在看。我是说为什么它出现在你的标题中?是“彩蛋”吗? :) - Laurence
@TheShiftExchange 是的 :) - 735Tesla
显示剩余4条评论
3个回答

5
尝试这个方法:在调用视图的控制器函数中,紧跟着调用'Response'类:
$contents = View::make('your_view')->with('data', $data);
$response = Response::make($contents, 200);
$response->header('X-Frame-Options','deny'); // Anti clickjacking
$response->header('X-XSS-Protection', '1; mode=block'); // Anti cross site scripting (XSS)
$response->header('X-Content-Type-Options', 'nosniff'); // Reduce exposure to drive-by dl attacks
$response->header('Content-Security-Policy', 'default-src \'self\''); // Reduce risk of XSS, clickjacking, and other stuff
    // Don't cache stuff (we'll be updating the page frequently)
$response->header('Cache-Control', 'nocache, no-store, max-age=0, must-revalidate');
$response->header('Pragma', 'no-cache');
$response->header('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');
return $response;

当然,您可以重构上述代码并将其包含在助手函数中。

$response->header('X-Archer', 'DANGER ZONE'); 为什么? - Lukas Bernhard
@LukasBernhard -- 你可以忽略那个自定义头。已删除。 - FredTheWebGuy
这对我不起作用,虽然类被继承为RESPONSE,但make()未定义。 - Sam

0

0
return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');

Laravel 5.8


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接