假如在域名b.com下,有一个html页面test.html,访问路径为:http://b.com/test.html;如果要防止别人在iframe下访问该页面,则可以通过nginx配置实现。
举例如下:
现有页面a.html,http://a.com/a.html,该页面有一个iframe,src=http://b.com/test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1 id="parent">引用页面</h1>
<iframe id="myIframe" src="http://b.com/test.html"></iframe>
</body>
</html>
被引用页面http://b.com/test.html,内容为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h2 id="被引用页面">test</h2>
</body>
</html>
配置过程:
1、打开nginx配置文件,在server、http或location的代码块里加入以下代码 :
1)add_header X-Frame-Options DENY;
此时访问http://a.com/a.html,则iframe提示:http://b.com/test.html拒绝了我们的连接请求,控制台报错:
Refused to display 'http://b.com/test.html' in a frame because it set 'X-Frame-Options' to 'deny'.
2)add_header X-Frame-Options SAMEORIGIN;
此时访问http://a.com/a.html,则iframe提示:http://b.com/test.html拒绝了我们的连接请求,控制台报错:
Refused to display 'http://b.com/test.html' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
2、重启nginx
如果设置 add_header X-Frame-Options ALLWOALL; 或者不配置X-Frame-Options,则http://b.com/test.html是可以在iframe中被引用的
试图通过指定域名可以访问,即设置:add_header X-Frame-Options "ALLOW-FROM http://a.com",但报错如下:
Invalid 'X-Frame-Options' header encountered when loading 'http://b.com/test.html': 'ALLOW-FROM http://a.com' is not a recognized directive. The header will be ignored.