插件窝 干货文章 nginx跨域怎么做

nginx跨域怎么做

Control Access 配置 header 393    来源:    2025-04-07

Nginx 跨域配置指南

在 Nginx 中配置跨域(CORS)可以通过添加特定的 HTTP 头部来实现。以下是完整的跨域配置解决方案:

基本跨域配置

server {
    listen 80;
    server_name example.com;

    location / {
        # 允许所有域名跨域访问
        add_header 'Access-Control-Allow-Origin' '*';

        # 允许的请求方法
        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';

        # 预检请求缓存时间
        add_header 'Access-Control-Max-Age' 1728000;

        # 允许浏览器在跨域请求中携带凭证(如cookies)
        # add_header 'Access-Control-Allow-Credentials' 'true';

        # 其他正常配置...
        proxy_pass http://backend;
    }
}

更安全的跨域配置(指定允许的域名)

map $http_origin $cors_origin {
    default "";
    "~^https://example.com$" $http_origin;
    "~^https://sub.example.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-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
            add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Max-Age' 1728000;
        }

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

        # 其他正常配置...
        proxy_pass http://backend;
    }
}

针对特定路径的跨域配置

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

    location /api/ {
        add_header 'Access-Control-Allow-Origin' 'https://example.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';

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

        proxy_pass http://backend;
    }

    # 其他location配置...
}

注意事项

  1. Access-Control-Allow-Credentials 设置为 true 时,Access-Control-Allow-Origin 不能使用通配符 *,必须指定具体域名
  2. 对于复杂请求(如PUT、DELETE或自定义头部的请求),浏览器会先发送OPTIONS预检请求
  3. 生产环境中建议不要使用 * 通配符,而是明确指定允许的域名
  4. 配置修改后需要重载Nginx:nginx -s reload

验证跨域配置

可以使用以下curl命令验证配置是否生效:

curl -I -X OPTIONS http://api.example.com/api/endpoint -H "Origin: https://example.com"

应该能看到返回的CORS相关头部信息。

以上配置可以根据实际需求进行调整,确保安全性和功能性的平衡。