插件窝 干货文章 Nginx搭建服务器的跨域访问配置和CORS协议支持指南

Nginx搭建服务器的跨域访问配置和CORS协议支持指南

Control Access header Allow 937    来源:    2025-04-13

Nginx跨域访问配置与CORS协议支持指南

什么是跨域问题

跨域问题源于浏览器的同源策略(Same-Origin Policy),它限制了来自不同源(协议、域名、端口)的资源交互。CORS(Cross-Origin Resource Sharing)是一种W3C标准,允许服务器声明哪些外部源可以访问其资源。

Nginx配置CORS支持

基本CORS配置

server {
    listen 80;
    server_name example.com;

    location / {
        # 允许所有来源访问(生产环境应更严格)
        add_header 'Access-Control-Allow-Origin' '*';

        # 允许的HTTP方法
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        # 允许的请求头
        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;

        # 允许浏览器在跨域请求中暴露响应头
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

        # 处理预检请求
        if ($request_method = 'OPTIONS') {
            return 204;
        }

        # 其他代理配置...
        proxy_pass http://backend;
    }
}

更安全的CORS配置

map $http_origin $cors_origin {
    default "";
    "~^https://(.*\.)?example\.com$" $http_origin;
    "~^https://(.*\.)?trusted-site\.com$" $http_origin;
}

server {
    listen 80;
    server_name api.example.com;

    location / {
        if ($cors_origin) {
            add_header 'Access-Control-Allow-Origin' $cors_origin;
            add_header 'Access-Control-Allow-Credentials' 'true';
        }

        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';

        if ($request_method = 'OPTIONS') {
            return 204;
        }

        proxy_pass http://backend;
    }
}

配置说明

  1. Access-Control-Allow-Origin

    • * 允许所有域访问(不推荐生产环境使用)
    • 指定具体域名更安全(如 https://example.com)
  2. Access-Control-Allow-Methods

    • 定义允许的HTTP方法(GET, POST等)
  3. Access-Control-Allow-Headers

    • 定义允许的请求头
  4. Access-Control-Allow-Credentials

    • 设置为true时允许发送凭据(cookies等)
  5. Access-Control-Max-Age

    • 预检请求结果的缓存时间(秒)
  6. OPTIONS请求处理

    • 预检请求使用OPTIONS方法,应直接返回204

常见问题解决方案

1. 预检请求失败

现象: 浏览器发送OPTIONS请求但返回404或405

解决: 确保Nginx正确处理OPTIONS方法:

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,Content-Type';
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 204;
}

2. 带凭据的请求被拒绝

现象: 使用withCredentials但请求失败

解决: 需要明确指定允许的来源(不能使用*)并启用凭据:

add_header 'Access-Control-Allow-Origin' 'https://client.example.com';
add_header 'Access-Control-Allow-Credentials' 'true';

3. 自定义头被拦截

现象: 自定义头如Authorization被拦截

解决: 在Allow-Headers中明确列出:

add_header 'Access-Control-Allow-Headers' 'Authorization, X-Custom-Header, Content-Type';

最佳实践

  1. 生产环境避免使用*作为允许的来源
  2. 根据实际需要最小化允许的方法和头
  3. 对于敏感操作,考虑结合其他安全措施如CSRF令牌
  4. 使用HTTPS确保跨域通信安全
  5. 定期审查和更新CORS策略

测试CORS配置

可以使用curl命令测试:

# 测试简单请求
curl -I -X GET https://api.example.com/resource -H "Origin: https://client.example.com"

# 测试预检请求
curl -I -X OPTIONS https://api.example.com/resource \
  -H "Origin: https://client.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Content-Type,Authorization"

通过合理配置Nginx的CORS支持,可以安全地实现跨域资源访问,同时保护API免受恶意利用。