使用HTTP 响应头信息中的 X-Frame-Options 属性防止网页被Frame

防止网页被Frame,方法有很多种;

方法一:常见的比如使用js,判断顶层窗口跳转:

js 代码:
  1. (function(){
  2. if(window != window.top){
  3. window.top.location.replace(window.location);//或者干别的事情
  4. }
  5. })();

一般这样够用了,但是有一次发现失效了,看了一下人家网站就是顶层窗口中的代码,发现这段代码:

js 代码:
  1. var location = document.location;
  2. // 或者 var location = "";

轻轻松松被破解了,悲剧。

 

注:此方式破解对IE6,IE7,IE9+、Chrome、firefox无效; 感谢@genify@_Franky 补充斧正。

方法二:meta 标签:基本没什么效果,所以也放弃了:

html 代码:
  1. <metahttp-equiv="Windows-Target"contect="_top">

方法三:使用HTTP 响应头信息中的 X-Frame-Options属性

使用 X-Frame-Options 有三个可选的值:

  1. DENY:浏览器拒绝当前页面加载任何Frame页面
  2. SAMEORIGIN:frame页面的地址只能为同源域名下的页面
  3. ALLOW-FROM:origin为允许frame加载的页面地址

绝大部分浏览器支持:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 4.1.249.1042 3.6.9 (1.9.2.9) 8.0 10.5 4.0

具体的设置方法:

Apache配置:

html 代码:
  1. Header always append X-Frame-Options SAMEORIGIN

nginx配置:

html 代码:
  1. add_header X-Frame-Options SAMEORIGIN;

IIS配置:

html 代码:
  1. <system.webServer>
  2. ...
  3.  
  4. <httpProtocol>
  5. <customHeaders>
  6. <addname="X-Frame-Options"value="SAMEORIGIN"/>
  7. </customHeaders>
  8. </httpProtocol>
  9.  
  10. ...
  11. </system.webServer>

具体可以查看:
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/X-Frame-Options?redirectlocale=en-US&redirectslug=The_X-FRAME-OPTIONS_response_header

猜你喜欢

转载自lishuaishuai.iteye.com/blog/2373751