Nginx配置跨域(CORS),这里的域指的是这样的


1 什么是跨域请求

跨域请求就是指:当前发起请求的域与该请求指向的资源所在的域不一样。这里的域指的是这样的一个概念:我们认为若协议 + 域名 + 端口号均相同,那么就是同域。

举个例子:假如一个域名为aaa.cn的网站,它发起一个资源路径为aaa.cn/books/getBookInfo的 Ajax 请求,那么这个请求是同域的,因为资源路径的协议、域名以及端口号与当前域一致(例子中协议名默认为http,端口号默认为80)。但是,如果发起一个资源路径为bbb.com/pay/purchase的 Ajax 请求,那么这个请求就是跨域请求,因为域不一致,与此同时由于安全问题,这种请求会受到同源策略限制。

2.常见跨域情况

  • 网络协议不同,如http协议访问https协议 ;
  • 端口不同,如80端口访问8080端口 ;
  • 域名不同,如www.test1.com访问www.test2.com ;
  • 子域名不同,如abc.test1.com访问def.test1.com ;

3 nginx跨域示例演示

准备一个nginx服务器,配置为

server {
      listen 80; # 监听的端⼝
       server_name www.zwx.com; # 域名或ip
      location / { # 访问路径配置   
      root /usr/share/nginx/html;# 根⽬录
      index index.html index.htm; # 默认⾸⻚
      }
      error_page 500 502 503 504 /50x.html; # 错误⻚⾯
      location = /50x.html {
      root html;
      }
}

在html目录里有一个wel.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nginx-cors-test</title>
</head>
<body>
<div>nginx跨域请求测试</div>

</body>

</html>

然后启动一个springboot应用,或者tomcat也可以,访问一个html页面

wel1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nginx-cors-test</title>
</head>
<body>
<button type="button" onclick="test()">nginx跨域请求测试</button>
<div id="test"></div>
</body>
<script src="jquery-1.10.2.min.js"></script>
<script>
    function test() {
        $.get("http://192.168.75.128/wel.html",null,function(result) {
            alert("跨域请求成功");
        });
    }

</script>
</html>

然后访问localhost:9000/wel1.html

点击测试按钮

出现了跨域访问错误

4 修改nginx server 配置

添加如下内容

server {
      listen 80; # 监听的端⼝
       server_name localhost; # 域名或ip
      location / { # 访问路径配置
  #允许跨域请求的域,* 代表所有
      add_header 'Access-Control-Allow-Origin' *;
      #允许带上cookie请求
      add_header 'Access-Control-Allow-Credentials' 'true';
      #允许请求的方法,比如 GET/POST/PUT/DELETE
      add_header 'Access-Control-Allow-Methods' *;
      #允许请求的header
      add_header 'Access-Control-Allow-Headers' *;
      root /usr/share/nginx/html;# 根⽬录
      index index.html index.htm; # 默认⾸⻚
      }
      error_page 500 502 503 504 /50x.html; # 错误⻚⾯
      location = /50x.html {
      root html;
      }
}

然后重启nginx再次测试

跨域求成功了

最重要的就是要在被跨域的nginx配置添加如下配置

      #允许跨域请求的域,* 代表所有
      add_header 'Access-Control-Allow-Origin' *;
      #允许带上cookie请求
      add_header 'Access-Control-Allow-Credentials' 'true';
      #允许请求的方法,比如 GET/POST/PUT/DELETE
      add_header 'Access-Control-Allow-Methods' *;
      #允许请求的header
      add_header 'Access-Control-Allow-Headers' *;

相关内容