确保 Laravel 网站的内容不会被嵌入到其他站点中


HTTP 响应头部中,有一个字段,叫做 X-Frame-Options,该字段可以用来指示是否允许自己的网站被嵌入到其他网站的 <iframe> 中。这个头部的值有三个

  • DENY - 全都不允许
  • SAMEORIGIN - 只允许同域名中嵌入
  • ALLOW-FROM uri - 设置允许的域

通常,可以在 HTTP 代理中进行配置,比如 nginx

add_header X-Frame-Options SAMEORIGIN;

Laravel 实际上自带了用来「只允许同域名嵌入」的中间件,我们只需要在 /app/Http/Kernel.php 中添加即可

protected $middleware = [
    ...
    \Illuminate\Http\Middleware\FrameGuard::class,
];

对应源码

<?php

namespace Illuminate\Http\Middleware;

use Closure;

class FrameGuard
{
    /**
     * Handle the given request and get the response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);

        return $response;
    }
}

点赞 取消点赞 收藏 取消收藏

<< 上一篇: Laravel 上一篇下一篇的小技巧,一般人不告诉他~

>> 下一篇: 10个你应该了解的php比特币开源项目