当前位置: 代码网 > it编程>数据库>Access > Nginx解决Access-Control-Allow-Origin跨域问题完全指南

Nginx解决Access-Control-Allow-Origin跨域问题完全指南

2026年03月21日 Access 我要评论
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档一、跨域问题概述1.1 什么是跨域问题?跨域问题是由于浏览器的同源策略(same-origin policy)限制导致的。当a服务器的前

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、跨域问题概述

1.1 什么是跨域问题?

跨域问题是由于浏览器的同源策略(same-origin policy)限制导致的。当a服务器的前端页面尝试访问b服务器的api时,浏览器会阻止这种跨域请求。

同源策略要求:

  • 协议相同(http/https)
  • 域名相同
  • 端口相同

只要其中一项不同,即为跨域请求。

二、nginx解决方案详解

2.1 完整的nginx配置示例

# nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
    worker_connections 1024;
}
http {
    # 包含mime类型定义
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log main;
    # 基本优化设置
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    # 主服务器配置
    server {
        listen 9800;
        server_name localhost;
        root /usr/share/nginx/html;
        # 默认首页
        index index.html index.htm;
        # ========== cors跨域配置 ==========
        # 处理options预检请求
        location / {
            # 如果是options请求,直接返回204
            if ($request_method = 'options') {
                add_header 'access-control-allow-origin' $http_origin;
                add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch';
                add_header 'access-control-allow-headers' 'authorization, content-type, accept, x-requested-with, x-auth-token, x-csrf-token, x-api-key';
                add_header 'access-control-allow-credentials' 'true';
                add_header 'access-control-max-age' 1728000;
                add_header 'content-type' 'text/plain; charset=utf-8';
                add_header 'content-length' 0;
                return 204;
            }
            # 非options请求,添加cors头部
            add_header 'access-control-allow-origin' $http_origin;
            add_header 'access-control-allow-credentials' 'true';
            add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch';
            add_header 'access-control-allow-headers' 'authorization, content-type, accept, x-requested-with, x-auth-token, x-csrf-token, x-api-key';
            add_header 'access-control-expose-headers' 'content-length, content-range';
            # 如果是前端静态文件,直接返回
            try_files $uri $uri/ /index.html;
        }
        # ========== 反向代理配置(代理b服务器api) ==========
        # 方式1:通用api代理(推荐)
        location ~ ^/api/(.*)$ {
            proxy_pass http://192.168.x.xxx:9830/$1$is_args$args;
            proxy_redirect off;
            # 代理设置
            proxy_set_header host $http_host;
            proxy_set_header x-real-ip $remote_addr;
            proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
            proxy_set_header x-forwarded-proto $scheme;
            proxy_set_header x-forwarded-host $server_name;
            proxy_set_header upgrade $http_upgrade;
            proxy_set_header connection "upgrade";
            # 超时设置
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
            # 缓冲区设置
            proxy_buffer_size 128k;
            proxy_buffers 4 256k;
            proxy_busy_buffers_size 256k;
            # cors头部(只在响应时添加)
            add_header 'access-control-allow-origin' $http_origin always;
            add_header 'access-control-allow-credentials' 'true' always;
            add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch' always;
            add_header 'access-control-allow-headers' 'authorization, content-type, accept, x-requested-with, x-auth-token, x-csrf-token, x-api-key' always;
            add_header 'access-control-expose-headers' 'content-length, content-range' always;
            # 处理options预检请求
            if ($request_method = 'options') {
                add_header 'access-control-allow-origin' $http_origin;
                add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch';
                add_header 'access-control-allow-headers' 'authorization, content-type, accept, x-requested-with, x-auth-token, x-csrf-token, x-api-key';
                add_header 'access-control-allow-credentials' 'true';
                add_header 'access-control-max-age' 1728000;
                add_header 'content-type' 'text/plain; charset=utf-8';
                add_header 'content-length' 0;
                return 204;
            }
        }
        # 方式2:特定路径代理(原示例中的配置)
        location ~ /quartz/ {
            proxy_pass http://192.168.x.xxx:9830;
            proxy_read_timeout 360s;
            proxy_send_timeout 360s;
            # 代理头部
            proxy_set_header host $http_host;
            proxy_set_header x-real-ip $remote_addr;
            proxy_set_header x-forwarded-proto $scheme;
            proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
            proxy_set_header x-forwarded-host $server_name;
            # cors头部配置
            add_header front-end-https on;
            add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch' always;
            add_header 'access-control-allow-origin' $http_origin always;
            add_header 'access-control-allow-credentials' 'true' always;
            add_header 'access-control-allow-headers' 'accept, authorization, cache-control, content-type, dnt, if-modified-since, keep-alive, origin, user-agent, x-mx-reqtoken, x-requested-with, x-auth-token, x-csrf-token, x-api-key' always;
            add_header 'access-control-expose-headers' 'content-length, content-range, x-total-count' always;
            # 缓存预检请求
            add_header 'access-control-max-age' 1728000;
        }
        # 错误页面配置
        error_page 404 /404.html;
        location = /404.html {
            root /usr/share/nginx/html;
        }
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
    # ========== 多个后端服务配置示例 ==========
    server {
        listen 9801;
        server_name api-proxy.example.com;
        # 代理多个后端服务
        location /service1/ {
            proxy_pass http://backend1:8080/;
            # ... cors配置同上
        }
        location /service2/ {
            proxy_pass http://backend2:8081/;
            # ... cors配置同上
        }
    }
}

2.2 配置详解

2.2.1 核心cors头部说明

# 允许的源(域名)
add_header 'access-control-allow-origin' $http_origin;
# 允许的http方法
add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch';
# 允许的请求头
add_header 'access-control-allow-headers' 'authorization, content-type, accept, x-requested-with';
# 是否允许发送cookie
add_header 'access-control-allow-credentials' 'true';
# 预检请求缓存时间(秒)
add_header 'access-control-max-age' 1728000;
# 暴露给客户端的响应头
add_header 'access-control-expose-headers' 'content-length, content-range';

2.2.2 变量说明

变量说明示例值
$http_origin请求头中的origin字段http://localhost:8080
$request_method请求方法get, post, options
$http_host请求的host头example.com:9800
$remote_addr客户端ip地址192.168.1.100
$scheme请求协议http, https

三、不同场景的配置方案

3.1 场景1:开发环境(允许所有源)

# 开发环境配置 - 允许所有来源
map $http_origin $cors_origin {
    default "*";
}
server {
    listen 9800;
    location /api/ {
        # 开发环境:允许所有来源
        add_header 'access-control-allow-origin' $cors_origin;
        add_header 'access-control-allow-credentials' 'true';
        add_header 'access-control-allow-methods' '*';
        add_header 'access-control-allow-headers' '*';
        # 处理options请求
        if ($request_method = 'options') {
            return 204;
        }
        proxy_pass http://backend:8080;
    }
}

3.2 场景2:生产环境(白名单限制)

# 生产环境配置 - 白名单控制
map $http_origin $cors_origin {
    # 默认不允许
    default "";
    # 允许的域名
    ~^https?://(www\.)?example\.com(:[0-9]+)?$ $http_origin;
    ~^https?://api\.example\.com(:[0-9]+)?$ $http_origin;
    ~^https?://localhost(:[0-9]+)?$ $http_origin;
    ~^https?://127\.0\.0\.1(:[0-9]+)?$ $http_origin;
}
server {
    listen 9800;
    location /api/ {
        # 只有在白名单内才添加cors头部
        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' 'authorization, content-type, accept, x-requested-with';
        }
        # 处理options请求
        if ($request_method = 'options') {
            if ($cors_origin != "") {
                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' 'authorization, content-type, accept, x-requested-with';
                add_header 'access-control-max-age' 1728000;
                add_header 'content-length' 0;
                return 204;
            }
        }
        proxy_pass http://backend:8080;
    }
}

3.3 场景3:微服务架构

# 微服务网关配置
upstream auth_service {
    server auth-service:8081;
}
upstream order_service {
    server order-service:8082;
}
upstream product_service {
    server product-service:8083;
}
server {
    listen 9800;
    # 认证服务
    location /auth/ {
        proxy_pass http://auth_service/;
        include /etc/nginx/conf.d/cors.conf;
    }
    # 订单服务
    location /orders/ {
        proxy_pass http://order_service/;
        include /etc/nginx/conf.d/cors.conf;
    }
    # 商品服务
    location /products/ {
        proxy_pass http://product_service/;
        include /etc/nginx/conf.d/cors.conf;
    }
}
# cors.conf - 统一的cors配置
add_header 'access-control-allow-origin' $http_origin;
add_header 'access-control-allow-credentials' 'true';
add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch';
add_header 'access-control-allow-headers' 'authorization, content-type, accept, x-requested-with, x-auth-token';
add_header 'access-control-expose-headers' 'content-length, content-range, x-total-count';
if ($request_method = 'options') {
    add_header 'access-control-allow-origin' $http_origin;
    add_header 'access-control-allow-methods' 'get, post, put, delete, options, patch';
    add_header 'access-control-allow-headers' 'authorization, content-type, accept, x-requested-with, x-auth-token';
    add_header 'access-control-max-age' 1728000;
    add_header 'content-length' 0;
    return 204;
}

四、常见问题与解决方案

4.1 问题1:add_header不生效

原因: nginx的add_header指令在错误页面或某些条件下可能不生效。

解决方案: 使用always参数

# 使用always确保头部始终添加
add_header 'access-control-allow-origin' $http_origin always;
add_header 'access-control-allow-credentials' 'true' always;

4.2 问题2:携带cookie时跨域失败

原因: 当使用access-control-allow-credentials: true时,不能使用通配符*作为源。

解决方案: 动态设置允许的源

# 动态获取请求的origin
add_header 'access-control-allow-origin' $http_origin;
add_header 'access-control-allow-credentials' 'true';
# 或者使用条件判断
if ($http_origin ~* (example\.com|localhost)) {
    add_header 'access-control-allow-origin' $http_origin;
    add_header 'access-control-allow-credentials' 'true';
}

4.3 问题3:options预检请求返回404

原因: 后端服务没有处理options请求。

解决方案: 在nginx层面处理options请求

location /api/ {
    # 单独处理options请求
    if ($request_method = 'options') {
        add_header 'access-control-allow-origin' $http_origin;
        add_header 'access-control-allow-methods' 'get, post, put, delete, options';
        add_header 'access-control-allow-headers' 'authorization, content-type, accept';
        add_header 'access-control-max-age' 1728000;
        add_header 'content-length' 0;
        return 204;
    }
    # 正常请求转发
    proxy_pass http://backend:8080;
}

4.4 问题4:websocket跨域问题

解决方案: 特殊处理websocket连接

location /ws/ {
    proxy_pass http://backend:8080;
    proxy_http_version 1.1;
    # websocket升级
    proxy_set_header upgrade $http_upgrade;
    proxy_set_header connection "upgrade";
    # cors配置
    add_header 'access-control-allow-origin' $http_origin;
    add_header 'access-control-allow-credentials' 'true';
    add_header 'access-control-allow-methods' 'get, post, options';
    add_header 'access-control-allow-headers' 'authorization, upgrade, connection';
}

五、测试与验证

5.1 测试脚本

// test-cors.html
<!doctype html>
<html>
<head>
    <title>cors测试</title>
</head>
<body>
    <h1>cors测试页面</h1>
    <button onclick="testcors()">测试跨域请求</button>
    <div id="result"></div>
    <script>
        async function testcors() {
            try {
                const response = await fetch('http://a服务器ip:9800/api/test', {
                    method: 'get',
                    credentials: 'include', // 携带cookie
                    headers: {
                        'content-type': 'application/json',
                        'authorization': 'bearer test-token'
                    }
                });
                const data = await response.json();
                document.getelementbyid('result').innerhtml = 
                    `<pre>成功: ${json.stringify(data, null, 2)}</pre>`;
            } catch (error) {
                document.getelementbyid('result').innerhtml = 
                    `<pre style="color:red">错误: ${error.message}</pre>`;
            }
        }
        // 预检请求测试
        async function testpreflight() {
            try {
                const response = await fetch('http://a服务器ip:9800/api/test', {
                    method: 'put',
                    credentials: 'include',
                    headers: {
                        'content-type': 'application/json',
                        'x-custom-header': 'custom-value'
                    },
                    body: json.stringify({ test: 'data' })
                });
                const data = await response.json();
                console.log('预检请求成功:', data);
            } catch (error) {
                console.error('预检请求失败:', error);
            }
        }
    </script>
</body>
</html>

5.2 使用curl测试

# 测试options预检请求
curl -x options http://a服务器ip:9800/api/test \
  -h "origin: http://localhost:8080" \
  -h "access-control-request-method: post" \
  -h "access-control-request-headers: authorization,content-type" \
  -v
# 测试正常请求
curl -x get http://a服务器ip:9800/api/test \
  -h "origin: http://localhost:8080" \
  -h "authorization: bearer test-token" \
  -v

5.3 nginx配置检查

# 检查nginx配置语法
nginx -t
# 重新加载配置(不重启)
nginx -s reload
# 查看nginx错误日志
tail -f /var/log/nginx/error.log
# 查看访问日志
tail -f /var/log/nginx/access.log

六、安全注意事项

6.1 安全建议

  1. 不要使用通配符*:在生产环境中,应明确指定允许的域名
  2. 限制允许的方法:只开放必要的http方法
  3. 限制允许的头部:只允许必要的请求头
  4. 设置合理的缓存时间access-control-max-age不宜设置过长
  5. 使用https:跨域请求应使用https加密传输

6.2 安全配置示例

# 安全增强的cors配置
map $http_origin $allowed_origin {
    # 明确允许的域名列表
    "https://www.example.com" "https://www.example.com";
    "https://api.example.com" "https://api.example.com";
    "https://staging.example.com" "https://staging.example.com";
    default "";
}
server {
    # ... 其他配置 ...
    location /api/ {
        # 仅对允许的源添加cors头部
        if ($allowed_origin != "") {
            add_header 'access-control-allow-origin' $allowed_origin;
            add_header 'access-control-allow-credentials' 'true';
            add_header 'access-control-allow-methods' 'get, post';
            add_header 'access-control-allow-headers' 'authorization, content-type';
            add_header 'access-control-expose-headers' 'x-ratelimit-limit, x-ratelimit-remaining';
            add_header 'access-control-max-age' 86400; # 24小时
        }
        # 安全相关的其他头部
        add_header x-frame-options "sameorigin" always;
        add_header x-content-type-options "nosniff" always;
        add_header x-xss-protection "1; mode=block" always;
        proxy_pass http://backend:8080;
    }
}

七、总结

通过nginx配置解决跨域问题是最常用且有效的方法之一。关键点总结:

  • 核心原理:通过反向代理和添加cors响应头解决跨域
  • 必须头部
    • access-control-allow-origin
    • access-control-allow-methods
    • access-control-allow-headers
    • access-control-allow-credentials(需要时)
  • 处理流程
    • 浏览器发送options预检请求
    • nginx直接响应或转发到后端
    • 添加必要的cors头部
    • 允许实际请求通过
  • 最佳实践
    • 开发环境可以宽松配置
    • 生产环境需要严格的白名单控制
    • 结合https提升安全性
    • 定期审查和更新配置

通过合理配置nginx,不仅可以解决跨域问题,还能提升系统的安全性、性能和可维护性。

到此这篇关于nginx解决access-control-allow-origin跨域问题完全指南的文章就介绍到这了,更多相关nginx access-control-allow-origin跨域内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com