使用nginx代理后CORS头消失

bwntbbo3  于 12个月前  发布在  Nginx
关注(0)|答案(1)|浏览(123)

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

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

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

# Generated by nginxconfig.io
# See nginxconfig.txt for the configuration share link

user nginx;
pid /var/run/nginx.pid;
worker_processes auto;
worker_rlimit_nofile 65535;

# Load modules
include /etc/nginx/modules-enabled/*.conf;

events {
    multi_accept on;
    worker_connections 65535;
}

http {
    charset utf-8;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    server_tokens off;
    log_not_found off;
    types_hash_max_size 2048;
    types_hash_bucket_size 64;
    client_max_body_size 16M;

    # MIME
    include mime.types;
    default_type application/octet-stream;

    # Logging
    access_log off;
    error_log /var/log/nginx/error.log warn;

    # Limits
    limit_req_log_level warn;
    limit_req_zone $binary_remote_addr zone=login:10m rate=60r/m;

    # SSL
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;

    # Mozilla Modern configuration
    ssl_protocols TLSv1.3;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 114.114.114.114 valid=60s;
    resolver_timeout 2s;

    # Connection header for WebSocket reverse proxy
    map $http_upgrade $connection_upgrade {
        default upgrade;
        "" close;
    }

    map $remote_addr $proxy_forwarded_elem {

        # IPv4 addresses can be sent as-is
        ~^[0-9.]+$ "for=$remote_addr";

        # IPv6 addresses need to be bracketed and quoted
        ~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\"";

        # Unix domain socket names cannot be represented in RFC 7239 syntax
        default "for=unknown";
    }

    map $http_forwarded $proxy_add_forwarded {

        # If the incoming Forwarded header is syntactically valid, append to it
        "~^(,[ \\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";

        # Otherwise, replace it
        default "$proxy_forwarded_elem";
    }

    # Load configs
    include /etc/nginx/conf.d/*.conf;

    # mywebsite
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name mywebsite;
        root /var/www/mywebsite.site/public;

        # SSL
        ssl_certificate /etc/nginx/ssl/mywebsite.crt;
        ssl_certificate_key /etc/nginx/ssl/mywebsite.key;

        # security headers
        add_header X-XSS-Protection "1; mode=block" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "no-referrer-when-downgrade" always;
        add_header Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline'; frame-ancestors 'self';" always;
        add_header Permissions-Policy "interest-cohort=()" always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

        # . files
        location ~ /\.(?!well-known) {
            deny all;
        }

        # logging
        error_log /var/log/nginx/error.log warn;

        # reverse proxy
        location /api/ {
            proxy_pass http://172.17.0.2:8080;
            proxy_set_header Host $host;
            proxy_http_version 1.1;
            proxy_cache_bypass $http_upgrade;

            # Proxy SSL
            proxy_ssl_server_name on;

            # Proxy headers
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Forwarded $proxy_add_forwarded;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Port $server_port;

            # Proxy timeouts
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

        # favicon.ico
        location = /favicon.ico {
            log_not_found off;
        }

        # robots.txt
        location = /robots.txt {
            log_not_found off;
        }

        # assets, media
        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)$ {
            expires 7d;
        }

        # svg, fonts
        location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
            add_header Access-Control-Allow-Origin "*";
            expires 7d;
        }

        # gzip
        gzip on;
        gzip_vary on;
        gzip_proxied any;
        gzip_comp_level 6;
        gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
    }

    # non-www, subdomains redirect
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name .mywebsite;

        # SSL
        ssl_certificate /etc/nginx/ssl/mywebsite.crt;
        ssl_certificate_key /etc/nginx/ssl/mywebsite.key;
        return 301 https://mysite$request_uri;
    }

    # HTTP redirect
    server {
        listen 80;
        listen [::]:80;
        server_name .mywebsite;
        return 301 https://www.mywebsite$request_uri;
    }
}


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

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

的字符串

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

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


在杜松子酒中添加标题

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


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

lymnna71

lymnna711#

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

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name .mywebsite;

        # SSL
        ssl_certificate /etc/nginx/ssl/mywebsite.crt;
        ssl_certificate_key /etc/nginx/ssl/mywebsite.key;
        return 307 https://mywebsite.site$request_uri;
    }

字符串

相关问题