一次 Nginx 跨域代理的完整排坑实录:从证书错误到 CORS 配置
一次 Nginx 跨域代理的完整排坑实录从证书错误到 CORS 配置关键词Nginx、CORS、跨域、SSL证书、反向代理、预检请求一、背景与需求最近在做一个项目架构如下前端域名https://www.example.com第三方APIhttps://thirdparty-api.example.net不支持 CORS目标前端需要调用该第三方 API但存在跨域问题解决方案使用 Nginx 做反向代理将请求转发到自己的子域名https://api.example.com并在 Nginx 层添加 CORS 响应头。预期请求链路浏览器 → api.example.com (Nginx) → thirdparty-api.example.net本以为是个简单的配置结果前后踩了6 个坑耗时整整一天。本文将完整记录排坑过程希望对遇到类似问题的朋友有所帮助。二、踩坑全记录坑位1SSL 证书域名不匹配错误现象ERR_CERT_COMMON_NAME_INVALID原因分析api.example.com使用了www.example.com的 SSL 证书导致浏览器校验证书时发现域名不匹配。解决方案为api.example.com申请独立的 SSL 证书certbot certonly--nginx-dapi.example.com教训每个子域名都需要自己的证书或使用通配符证书*.example.com。坑位2CORS 预检请求失败错误现象Access to fetch at https://api.example.com/... from origin https://www.example.com has been blocked by CORS policy: No Access-Control-Allow-Origin header is present原因分析浏览器在发送实际请求前会先发送一个OPTIONS预检请求。Nginx 没有正确处理这个请求也没有返回必要的 CORS 响应头。解决方案在 Nginx 配置中添加 CORS 头和 OPTIONS 请求处理location / { # CORS 响应头 add_header Access-Control-Allow-Origin https://www.example.com always; add_header Access-Control-Allow-Methods GET, POST, OPTIONS always; add_header Access-Control-Allow-Headers Content-Type, Authorization always; add_header Access-Control-Allow-Credentials true always; # 处理预检请求 if ($request_method OPTIONS) { add_header Content-Length 0; add_header Content-Type text/plain charsetutf-8; return 204; } # 代理配置... }坑位3add_header 语法错误错误现象[emerg] add_header directive is not allowed here in /etc/nginx/conf.d/ssl.conf:47原因分析add_header指令被放在了 Nginx 不允许的位置。这个指令只能出现在http、server、location块中不能随意放置。错误示例server { # 正确位置 add_header Header1 value1 always; location / { # 正确位置 add_header Header2 value2 always; } } # ❌ 错误在 server/location 块外面 add_header Header3 value3 always;解决方案确保所有add_header都在server或location块内部。坑位4Access-Control-Allow-Origin 重复错误现象The Access-Control-Allow-Origin header contains multiple values https://www.example.com, https://www.example.com, but only one is allowed.原因分析Nginx 配置中add_header Access-Control-Allow-Origin ...被写了两次导致响应头中出现重复值。解决方案检查配置文件确保每个 CORS 头只添加一次。如果同时在server和location块中添加了保留一处即可。坑位5代理 Host 头不正确错误现象后端 API 返回 502 或 404但直接访问后端 API 是正常的。原因分析默认情况下proxy_set_header Host $host会将 Host 头设置为api.example.com而后端 API 可能期望的是自己的域名thirdparty-api.example.net。解决方案使用$proxy_host变量它保存的是proxy_pass中指定的域名# ❌ 错误Host 头变成 api.example.com proxy_set_header Host $host; # ✅ 正确Host 头保持 thirdparty-api.example.net proxy_set_header Host $proxy_host;坑位6后端使用 HTTPS 导致证书问题错误现象Nginx 代理到https://thirdparty-api.example.net时出现 SSL 错误。原因分析Nginx 作为代理去访问 HTTPS 后端时需要验证后端证书。如果后端证书有问题自签名、过期、域名不匹配等Nginx 会拒绝连接。解决方案有两种方式方案A推荐使用 HTTP 协议代理# 如果后端支持 HTTP直接用 HTTP proxy_pass http://thirdparty-api.example.net$request_uri;方案B忽略证书验证仅临时使用proxy_pass https://thirdparty-api.example.net$request_uri; proxy_ssl_verify off; # 关闭证书验证三、最终正确的配置经过以上所有坑位的修复最终配置如下server { listen 443 ssl; server_name api.example.com; # DNS 解析器使用域名代理时推荐添加 resolver 114.114.114.114 223.5.5.5 valid30s; resolver_timeout 10s; # SSL 证书使用子域名自己的证书 ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # HSTS 安全头 add_header Strict-Transport-Security max-age31536000; includeSubDomains; preload always; # SSL 配置 ssl_session_timeout 1d; ssl_session_cache shared:MozSSL:10m; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers off; client_max_body_size 100M; location / { # CORS 配置 add_header Access-Control-Allow-Origin https://www.example.com always; add_header Access-Control-Allow-Methods GET, POST, OPTIONS always; add_header Access-Control-Allow-Headers Content-Type, Authorization always; add_header Access-Control-Allow-Credentials true always; # 处理预检请求 if ($request_method OPTIONS) { add_header Content-Length 0; add_header Content-Type text/plain charsetutf-8; return 204; } # 代理配置 # 核心转发使用 HTTP 避免后端证书问题 proxy_pass http://thirdparty-api.example.net$request_uri; # 关键使用 $proxy_host 保持原始 Host proxy_set_header Host $proxy_host; # 传递真实客户端信息 proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # HTTP 1.1 支持 proxy_http_version 1.1; proxy_set_header Connection ; # 超时设置 proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; # API 最佳实践禁用缓存 proxy_buffering off; proxy_cache off; } } # HTTP 重定向到 HTTPS server { listen 80; server_name api.example.com; return 301 https://$server_name$request_uri; }四、核心经验总结1. 关于 SSL 证书要点说明子域名需要独立证书api.example.com不能使用www.example.com的证书申请命令certbot certonly --nginx -d api.example.com通配符证书*.example.com可以覆盖所有子域名2. 关于 CORS 配置要点说明必须处理 OPTIONS浏览器预检请求需要返回 204头不能重复Access-Control-Allow-Origin只能出现一次位置限制add_header只能在server/location块内3. 关于代理转发要点说明Host 头用$proxy_host保持后端期望的域名添加$request_uri完整传递请求路径后端可以用 HTTP浏览器到 Nginx 需要 HTTPSNginx 到后端可以用 HTTP4. 调试技巧# 测试 Nginx 配置语法nginx-t# 查看错误日志tail-f/var/log/nginx/error.log# 测试 CORS 响应头curl-XOPTIONS https://api.example.com/api/test\-HOrigin: https://www.example.com\-HAccess-Control-Request-Method: POST\-v21|grep-iaccess-control五、一个重要的认知Postman 能请求成功 ≠ 浏览器能请求成功工具是否检查 CORS说明Postman❌ 不检查桌面应用不受浏览器安全策略限制curl❌ 不检查命令行工具浏览器✅ 严格检查为了用户安全必须配置正确的 CORS这个认知能帮助您在调试时快速定位问题Postman 通但浏览器不通 → 99% 是 CORS 配置问题。六、架构总结最终的成功架构浏览器 -----------(HTTPS)----------- Nginx -----------(HTTP)----------- 后端 (www.example.com) (api.example.com) (thirdparty-api) ↑ ↑ ↑ 安全连接 SSL证书 CORS头 内部通信关键设计思想浏览器到 Nginx必须 HTTPS证书有效Nginx 到后端可以用 HTTP避免证书麻烦Nginx 层统一处理 CORS后端无需改造七、写在最后这次排坑让我深刻体会到Nginx 配置顺序和位置非常重要一个小错误就能导致整个服务不可用CORS 不是后端的事是 Nginx/网关层的事统一处理比每个后端服务单独配置要优雅得多HTTPS 是端到端的但中间代理可以用 HTTP 转发不影响整体安全性遇到问题先看日志Nginx 的错误日志非常详细能定位 90% 的问题希望这篇文章能帮助到正在被 Nginx 跨域问题困扰的您。如果您有更好的实践或发现文章中的错误欢迎交流讨论相关文章推荐MDN: CORS 跨域资源共享Nginx 官方文档ngx_http_proxy_moduleLet’s Encrypt 免费 SSL 证书申请指南
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2499546.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!