HTTP 響應頭部中,有一個字段,叫做 X-Frame-Options,該字段可以用來指示是否允許自己的網站被嵌入到其他網站的 <iframe> 或者 <object> 標簽中。該頭部有三個值
- DENY - 始終不允許嵌入,即使是同一個域名
- SAMEORIGIN - 只能在相同域名中嵌入
- ALLOW-FROM uri - 設置允許的域
通常,可以在 HTTP 代理中進行配置,比如 nginx
1
|
add_header X-Frame-Options SAMEORIGIN; |
Laravel 自帶了用來「只允許同域名嵌入」的中間件,我們只需要在 /app/Http/Kernel.php 中添加即可
1
2
3
4
|
// /app/Http/Kernel.php protected $middleware = [ \Illuminate\Http\Middleware\FrameGuard:: class , ]; |
該中間件的實現如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?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 ; } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://learnku.com/articles/35201