说明
后端接口在浏览器中被访问的时候,经常会遇到跨域的情况,通过后端程序可以进行跨域配置,但生产环境通常都是配置在代理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' '*';