亿琪软件-开源博客 - 代理
type: channel
link: https://www.yiqisoft.cn/blogs/tag/%E4%BB%A3%E7%90%86/
items: 分享- Nginx 代理后，CORS 跨域问题解决思路

分享- Nginx 代理后，CORS 跨域问题解决思路
type: item
date: 2025-03-16T05:43:00+00:00
description: 前提 浏览器提示 CORS 问题 设置相关 主网站 被动网站 前提 当我们访问网站：demo.a.com 时，会顺便访问 *.t.a.com 时，会造成 CORS 问题。 浏览器提示 CORS 问题 不用多说，CORS 问题一直存在，现在必须要要解决掉。 设置相关 假设，两个网站都是使用 Nginx 作为反向代理。 主网站 server { root /var/www/html/demo.a.com; server_name: demo.a.com; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } # CORS 配置 add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always; ... } 被动网站 server { root /var/www/html/t.a.com; server_name .t.a.com; location / { # 处理预检请求 if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Authorization, DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } # CORS 配置 add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'Authorization, DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range' always; proxy_pass http://localhost:8888; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header …