nginx配置跨域访问

说明

后端接口在浏览器中被访问的时候,经常会遇到跨域的情况,通过后端程序可以进行跨域配置,但生产环境通常都是配置在代理web服务器上,这里就以nginx为例。网上搜了怎么配置跨域的问题,很多并没有真正的真正解决问题,最近重新复盘了一遍,希望可以帮助到大家。

配置方法

if ($request_method = 'OPTIONS') {
	add_header 'Access-Control-Allow-Origin' $http_origin;
	add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
	add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token,Authorization,postman-token';
	add_header 'Access-Control-Max-Age' 1728000;
	return 204;
}
add_header 'Access-Control-Allow-Origin' $http_origin;

完整配置文件

server {
    listen       80;
    listen  [::]:80;
    server_name  www.chinoukin.xyz;
    #rewrite ^/(.*)$ https://www.chinoukin.xyz:443/$1 permanent;
	
	#把http的域名请求转成https
    return 301 https://$host$request_uri; 
}


server {
    listen       443 ssl;
    server_name  www.chinoukin.xyz;

    #从腾讯云获取到的第一个文件的全路径
    ssl_certificate /etc/nginx/conf.d/1_chinoukin.xyz_bundle.crt;
    #从腾讯云获取到的第二个文件的全路径
    ssl_certificate_key /etc/nginx/conf.d/2_chinoukin.xyz.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;


	underscores_in_headers on;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location ~ ^/(env|item/ts) {
		if ($request_method = 'OPTIONS') {
			add_header 'Access-Control-Allow-Origin' $http_origin;
			add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
			add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token,Authorization,postman-token';
			add_header 'Access-Control-Max-Age' 1728000;
			return 204;
		}
		add_header 'Access-Control-Allow-Origin' $http_origin;

        proxy_set_header   Host $host;
        proxy_set_header   X-real-ip  $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
		proxy_pass http://172.21.0.15:8080;
    } 

#   location /echo {
#		echo $remote_addr;
#	}
 
}

其他

也可以将Access-Control-Allow-Headers配置为"*",允许跨域携带任何的header,如下:

add_header 'Access-Control-Allow-Headers' '*';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值