只需一个配置,轻松解决X-Frame-Options跨域问题
效果展示:
1、存在问题:
2、解决问题
对iframe引入的http://com.ityj.frame/xframe/hello
项目,通过nginx过滤掉X-Frame-Options的配置
操作如下:
location / {
#root html;
#index index.html index.htm;
proxy_pass http://com.ityj.frame;
proxy_hide_header X-Frame-Options; # 避免出现多个X-Frame-Options属性
add_header X-Frame-Options ALLOWALL; # 将之前网页的SAMEORIGIN属性给替换了,可以嵌套了
}
修改后保存,重新加载nginx./nginx -s reload
,并重新打开页面或者ctrl + F5刷新
可以正常使用iframe嵌套并访问了!!!
3、其他
nginx完整配置如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#gzip on;
# 注意,这里的server名字即org.tonny.balance不能带下划线
# upstream com.ityj.redis {
# server localhost:1111 weight=1;
# server localhost:2222 weight=1;
# }
upstream com.ityj.frame {
server localhost:8181;
}
server {
listen 80;
server_name localhost;
#location / {
#root html;
#index index.html index.htm;
# proxy_pass http://com.ityj.redis;
#}
location / {
#root html;
#index index.html index.htm;
proxy_pass http://com.ityj.frame;
proxy_hide_header X-Frame-Options; # 避免出现多个X-Frame-Options属性
add_header X-Frame-Options ALLOWALL;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
1、其中http://com.ityj.frame就是有X-Frame-Options的服务器,nginx就是针对其进行过滤处理。
手动产生有x-frame-options的请求
@RequestMapping(path = "/hello")
public void sayHello(HttpServletResponse response) throws IOException {
System.out.println("response...");
response.addHeader("x-frame-options","SAMEORIGIN");
response.setContentType("text/html; charset=UTF-8");
response.getWriter().write("<h1>哈哈哈哈</h1>");
}
2、使用iframe进行嵌套的程序
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF‐8">
<title>Index</title>
<script th:src="@{webjars/jquery/3.3.1/jquery.min.js}"></script>
<script>
$(function () {
changeUrl();
})
function changeUrl() {
var tempValue = $("#codSelect option:selected").attr("temp");
$("#iframeId").attr("src", tempValue);
}
</script>
</head>
<body>
<h1>Welcome</h1>
<div>
<form>
<span>请选择:</span>
<select id="codSelect" th:onchange="changeUrl()">
<option th:each="codAndUrl : ${codAndUrlMap}" th:value="${codAndUrl.key}" th:text="${codAndUrl.key}" th:temp="${codAndUrl.value}"></option>
</select>
</form>
</div>
<br/>
<iframe id="iframeId" src="https://mybatis.org/mybatis-3/zh/getting-started.html" style="position: relative; width: 100%; height: 600px"></iframe>
</body>
</html>
@RestController
@Slf4j
public class IndexController {
@GetMapping(path = {"/toIndex", "/", ""})
public ModelAndView toIndex() {
log.info("get into toIndex()...");
ModelAndView mv = new ModelAndView();
Map<String, String> codAndUrlMap = new LinkedHashMap<>();
codAndUrlMap.put("斗鱼", "https://www.douyu.com/");
codAndUrlMap.put("百度问题", "https://www.baidu.com/");
codAndUrlMap.put("Google", "https://www.google.com/");
codAndUrlMap.put("XFRAME", "http://com.ityj.frame/xframe/hello");
mv.addObject("codAndUrlMap", codAndUrlMap);
mv.setViewName("index");
return mv;
}
}