PHP、Nginx、Apache中禁止网页被iframe引用的方法

(编辑:jimmy 日期: 2026/1/29 浏览:2)

可以使用php或nginx等添加X-Frame-Options header来控制frame权限
X-Frame-Options有三个可选的值:

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

PHP代码:

header(‘X-Frame-Options:Deny');

Nginx配置:

add_header X-Frame-Options SAMEORIGIN

可以加在locaion中

location /
{
  add_header X-Frame-Options SAMEORIGIN
}

Apache配置:

Header always append X-Frame-Options SAMEORIGIN

使用后不充许frame的页面会显示一个白板。

IIS方法

在web.config文件中加

<system.webServer>
  ...
  <httpProtocol>
  <customHeaders>
  <add name="X-Frame-Options" value="SAMEORIGIN" />
  </customHeaders>
  </httpProtocol>
  ...
</system.webServer>

js方法

很多都是用这种方放,服务器端设置有时候有问题

if (self.frameElement && self.frameElement.tagName == "IFRAME") {
  top.location.href=self.location.href;
}
if (window.frames.length != parent.frames.length) {
  top.location.href=self.location.href;
}
if (self != top) { 
  top.location.href=self.location.href;
}

Meta标签方法

<meta http-equiv="X-FRAME-OPTIONS" content="DENY">

css禁止其他人的iframe,允许自己的

<style type="text/css">
iframe{v:expression (this.src='about:blank',this.outerHTML='');}
#mine{v:expression() !important}
</style>
<body> 内容:<iframe src="/UploadFiles/2021-04-02/www.baidu.com">

参考:

https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options?redirectlocale=en-US&redirectslug=The_X-FRAME-OPTIONS_response_header

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。