Nginx 跨域(CORS)配置详细介绍

跨域资源共享(CORS)是现代浏览器安全策略的一部分,Nginx可以通过配置响应头来解决跨域问题。以下是完整的配置方案:

基础跨域配置

在Nginx配置文件的 serverlocation 块中添加以下指令:

location / {
    # 允许所有域名跨域访问(生产环境应限制为具体域名)
    add_header 'Access-Control-Allow-Origin' '*';
    
    # 允许的请求方法
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
    
    # 允许的请求头
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
    
    # 预检请求(OPTIONS)缓存时间
    add_header 'Access-Control-Max-Age' 1728000;
    
    # 允许浏览器在跨域请求中携带Cookie
    add_header 'Access-Control-Allow-Credentials' 'true';
    
    # 处理OPTIONS预检请求
    if ($request_method = 'OPTIONS') {
        return 204;
    }
}

生产环境推荐配置

map $http_origin $cors_origin {
    default "";
    "~^https://(www\.)?yourdomain\.com$" $http_origin;
    "~^https://(.*\.)?yourotherdomain\.com$" $http_origin;
}

server {
    location /api/ {
        # 动态设置允许的源
        add_header 'Access-Control-Allow-Origin' $cors_origin;
        
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
        add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range';
        add_header 'Access-Control-Allow-Credentials' 'true';
        
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        
        # 你的其他代理配置...
        proxy_pass http://backend;
    }
}

常见问题解决方案

  1. 多个域名配置

    map $http_origin $cors_origin {
        default "";
        "~^https://(www\.)?domain1\.com$" $http_origin;
        "~^https://(www\.)?domain2\.com$" $http_origin;
    }
    
  2. 携带Cookie问题

    • 必须指定具体域名(不能是*)
    • 必须设置 Access-Control-Allow-Credentials: true
    • 前端需要设置 withCredentials: true
  3. 自定义头问题

    add_header 'Access-Control-Allow-Headers' 'X-Custom-Header, Authorization';
    
  4. Vue/React开发环境代理

    location /api {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        # 跨域头设置...
    }
    

配置测试方法

  1. 检查Nginx配置语法:

    sudo nginx -t
    
  2. 重载Nginx配置:

    sudo nginx -s reload
    
  3. 使用curl测试:

    curl -I -X OPTIONS http://yourdomain.com/api -H "Origin: http://test.com"
    
  4. 浏览器开发者工具检查响应头

注意事项

  1. 生产环境不要使用 Access-Control-Allow-Origin: *Access-Control-Allow-Credentials: true 同时存在
  2. 对于简单请求(GET/POST/HEAD)和预检请求(OPTIONS)都要正确处理
  3. 缓存控制头不要覆盖CORS头
  4. 使用HTTPS时确保所有来源也是HTTPS

正确配置CORS可以确保你的API安全地支持跨域访问,同时防止CSRF等安全问题。

要在Nginx配置CORS源资源共享),您需要编辑Nginx配置文件并添加相关配置。 首先,打开Nginx配置文件。默认情况下,该文件通常位于以下位置之一: - /etc/nginx/nginx.conf - /etc/nginx/conf.d/default.conf 找到您希望启用CORS的服务器块或位置块,并在其中添加以下配置: ``` location / { # 允许的来源(名) if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } # 其他配置... } ``` 在上面的配置中,我们允许所有来源('*')访问。您可以根据需要更改为特定的名。 配置完成后,保存文件并重新加载Nginx配置,以使更改生效。您可以使用以下命令重新加载Nginx: ``` sudo service nginx reload ``` 现在,您的Nginx服务器应该已经启用了CORS,并允许访问。请确保您的应用程序也正确处理CORS 头部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值