使用nginx代理后CORS头消失

bwntbbo3  于 2024-01-06  发布在  Nginx
关注(0)|答案(1)|浏览(154)

我的小项目使用go作为后端,并利用gincors来设置cors头,并在docker中设置它

  1. r.Use(cors.New(cors.Config{
  2. AllowAllOrigins: true,
  3. AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"},
  4. AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
  5. AllowCredentials: true,
  6. MaxAge: 12 * time.Hour,
  7. }))

字符串
直接打开服务器端口,一切正常,前端正常接收相关的响应头。但是当我用nginx和代理/API请求部署前端到后端时,浏览器总是提示
从源“mywebsite”访问"mywebsite/API“处的XMLHttpRequest已被CORS策略阻止:请求的资源上不存在”MyWebsite-Control-Allow-Origin“标头。
我检查了响应头,所有与cors相关的头都没有了。当我使用用于绕过此限制的浏览器插件进行测试时,一切正常,表明代理成功。这是我的nginx配置,由工具生成

  1. # Generated by nginxconfig.io
  2. # See nginxconfig.txt for the configuration share link
  3. user nginx;
  4. pid /var/run/nginx.pid;
  5. worker_processes auto;
  6. worker_rlimit_nofile 65535;
  7. # Load modules
  8. include /etc/nginx/modules-enabled/*.conf;
  9. events {
  10. multi_accept on;
  11. worker_connections 65535;
  12. }
  13. http {
  14. charset utf-8;
  15. sendfile on;
  16. tcp_nopush on;
  17. tcp_nodelay on;
  18. server_tokens off;
  19. log_not_found off;
  20. types_hash_max_size 2048;
  21. types_hash_bucket_size 64;
  22. client_max_body_size 16M;
  23. # MIME
  24. include mime.types;
  25. default_type application/octet-stream;
  26. # Logging
  27. access_log off;
  28. error_log /var/log/nginx/error.log warn;
  29. # Limits
  30. limit_req_log_level warn;
  31. limit_req_zone $binary_remote_addr zone=login:10m rate=60r/m;
  32. # SSL
  33. ssl_session_timeout 1d;
  34. ssl_session_cache shared:SSL:10m;
  35. ssl_session_tickets off;
  36. # Mozilla Modern configuration
  37. ssl_protocols TLSv1.3;
  38. # OCSP Stapling
  39. ssl_stapling on;
  40. ssl_stapling_verify on;
  41. resolver 114.114.114.114 valid=60s;
  42. resolver_timeout 2s;
  43. # Connection header for WebSocket reverse proxy
  44. map $http_upgrade $connection_upgrade {
  45. default upgrade;
  46. "" close;
  47. }
  48. map $remote_addr $proxy_forwarded_elem {
  49. # IPv4 addresses can be sent as-is
  50. ~^[0-9.]+$ "for=$remote_addr";
  51. # IPv6 addresses need to be bracketed and quoted
  52. ~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\"";
  53. # Unix domain socket names cannot be represented in RFC 7239 syntax
  54. default "for=unknown";
  55. }
  56. map $http_forwarded $proxy_add_forwarded {
  57. # If the incoming Forwarded header is syntactically valid, append to it
  58. "~^(,[ \\t]*)*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?)*([ \\t]*,([ \\t]*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?)*)?)*$" "$http_forwarded, $proxy_forwarded_elem";
  59. # Otherwise, replace it
  60. default "$proxy_forwarded_elem";
  61. }
  62. # Load configs
  63. include /etc/nginx/conf.d/*.conf;
  64. # mywebsite
  65. server {
  66. listen 443 ssl http2;
  67. listen [::]:443 ssl http2;
  68. server_name mywebsite;
  69. root /var/www/mywebsite.site/public;
  70. # SSL
  71. ssl_certificate /etc/nginx/ssl/mywebsite.crt;
  72. ssl_certificate_key /etc/nginx/ssl/mywebsite.key;
  73. # security headers
  74. add_header X-XSS-Protection "1; mode=block" always;
  75. add_header X-Content-Type-Options "nosniff" always;
  76. add_header Referrer-Policy "no-referrer-when-downgrade" always;
  77. add_header Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline'; frame-ancestors 'self';" always;
  78. add_header Permissions-Policy "interest-cohort=()" always;
  79. add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
  80. # . files
  81. location ~ /\.(?!well-known) {
  82. deny all;
  83. }
  84. # logging
  85. error_log /var/log/nginx/error.log warn;
  86. # reverse proxy
  87. location /api/ {
  88. proxy_pass http://172.17.0.2:8080;
  89. proxy_set_header Host $host;
  90. proxy_http_version 1.1;
  91. proxy_cache_bypass $http_upgrade;
  92. # Proxy SSL
  93. proxy_ssl_server_name on;
  94. # Proxy headers
  95. proxy_set_header Upgrade $http_upgrade;
  96. proxy_set_header Connection $connection_upgrade;
  97. proxy_set_header X-Real-IP $remote_addr;
  98. proxy_set_header Forwarded $proxy_add_forwarded;
  99. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  100. proxy_set_header X-Forwarded-Proto $scheme;
  101. proxy_set_header X-Forwarded-Host $host;
  102. proxy_set_header X-Forwarded-Port $server_port;
  103. # Proxy timeouts
  104. proxy_connect_timeout 60s;
  105. proxy_send_timeout 60s;
  106. proxy_read_timeout 60s;
  107. }
  108. # favicon.ico
  109. location = /favicon.ico {
  110. log_not_found off;
  111. }
  112. # robots.txt
  113. location = /robots.txt {
  114. log_not_found off;
  115. }
  116. # assets, media
  117. location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
  118. expires 7d;
  119. }
  120. # svg, fonts
  121. location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
  122. add_header Access-Control-Allow-Origin "*";
  123. expires 7d;
  124. }
  125. # gzip
  126. gzip on;
  127. gzip_vary on;
  128. gzip_proxied any;
  129. gzip_comp_level 6;
  130. gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
  131. }
  132. # non-www, subdomains redirect
  133. server {
  134. listen 443 ssl http2;
  135. listen [::]:443 ssl http2;
  136. server_name .mywebsite;
  137. # SSL
  138. ssl_certificate /etc/nginx/ssl/mywebsite.crt;
  139. ssl_certificate_key /etc/nginx/ssl/mywebsite.key;
  140. return 301 https://mysite$request_uri;
  141. }
  142. # HTTP redirect
  143. server {
  144. listen 80;
  145. listen [::]:80;
  146. server_name .mywebsite;
  147. return 301 https://www.mywebsite$request_uri;
  148. }
  149. }


经过长时间的搜索,我已经尝试了各种各样的东西,如
在nginx配置中添加规则:

  1. add_header 'Access-Control-Allow-Origin' "*";
  1. add_header 'Access-Control-Allow-Origin' "$http_origin";

的字符串

  • 添加始终
  1. add_header 'Access-Control-Allow-Origin' "*" always;

  • 添加类型判断
  1. if ($request_method = 'OPTIONS') {
  2. add_header 'Access-Control-Allow-Origin' "*";
  3. return 204
  4. }


在杜松子酒中添加标题

  1. c.Header("Access-Control-Allow-Origin", "*")


从后端删除cors函数,仅用于nginx
它们都不工作。

lymnna71

lymnna711#

我发现这个解决方案https://www.lcgod.com/articles/94它看起来像nginx的重定向301将导致头部丢失,更改状态码为307来解决这个问题.

  1. server {
  2. listen 443 ssl http2;
  3. listen [::]:443 ssl http2;
  4. server_name .mywebsite;
  5. # SSL
  6. ssl_certificate /etc/nginx/ssl/mywebsite.crt;
  7. ssl_certificate_key /etc/nginx/ssl/mywebsite.key;
  8. return 307 https://mywebsite.site$request_uri;
  9. }

字符串

相关问题