Nginx反向代理跨域基本配置方法

发布时间:2022-04-27 14:10:25 作者:zzz
来源:亿速云 阅读:701
# Nginx反向代理跨域基本配置方法

## 一、跨域问题概述

### 1.1 什么是跨域问题
跨域问题源于浏览器的同源策略(Same-Origin Policy),该策略限制了一个源的文档或脚本如何与另一个源的资源进行交互。当协议、域名或端口任一不同时,就会产生跨域问题。

典型错误提示:

Access-Control-Allow-Origin’ header is present on the requested resource


### 1.2 常见解决方案对比
1. **JSONP**:仅支持GET请求
2. **CORS**:需要服务端配合设置响应头
3. **WebSocket**:协议升级方案
4. **反向代理**:最彻底的解决方案

## 二、Nginx反向代理原理

### 2.1 反向代理工作机制

客户端 → Nginx → 后端服务 ↑ 统一域名和端口


### 2.2 解决跨域的本质
通过将不同域的接口代理到同域下:

http://api.example.comhttp://www.example.com/api


## 三、基础配置实现

### 3.1 最小化配置示例
```nginx
server {
    listen       80;
    server_name  localhost;

    location /api/ {
        proxy_pass http://backend-server:8080/;
        
        # 核心跨域配置
        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,Content-Type';
        
        # 处理预检请求
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
}

3.2 关键指令解析

proxy_pass

proxy_pass http://target-server/uri/;

注意尾部斜杠的区别: - 带斜杠:替换匹配的location路径 - 不带斜杠:追加到proxy_pass末尾

add_header

必须配合always参数确保所有响应都包含头:

add_header 'Access-Control-Expose-Headers' 'Content-Length' always;

四、进阶配置方案

4.1 多项目路由配置

location ~ ^/(api|auth)/ {
    proxy_pass http://microservices/$1;
    
    # 透传原始域名
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

4.2 WebSocket代理

location /ws/ {
    proxy_pass http://websocket-server;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

4.3 负载均衡配置

upstream backend {
    server 10.0.0.1:8000 weight=5;
    server 10.0.0.2:8000;
    keepalive 32;
}

location / {
    proxy_pass http://backend;
}

五、安全加固配置

5.1 限制允许的源

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

server {
    add_header 'Access-Control-Allow-Origin' $cors_origin;
}

5.2 防止头信息伪造

proxy_hide_header X-Powered-By;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

5.3 速率限制

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

location /api/ {
    limit_req zone=api burst=20;
}

六、常见问题排查

6.1 502 Bad Gateway

检查项: 1. 后端服务是否运行 2. 防火墙规则 3. DNS解析是否正常

6.2 跨域头未生效

可能原因: 1. 存在重复的add_header指令 2. 被后端服务覆盖头信息 3. 需要添加always参数

6.3 缓存问题解决方案

location /static/ {
    proxy_cache my_cache;
    proxy_cache_valid 200 304 12h;
    proxy_cache_use_stale error timeout updating;
}

七、性能优化建议

7.1 连接池配置

proxy_http_version 1.1;
proxy_set_header Connection "";
keepalive_timeout 75s;

7.2 缓冲区优化

proxy_buffers 16 32k;
proxy_buffer_size 64k;
proxy_busy_buffers_size 128k;

7.3 超时设置

proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

八、完整配置示例

http {
    upstream backend {
        server 10.0.0.1:8000;
        server 10.0.0.2:8000;
    }

    server {
        listen 443 ssl;
        server_name api.example.com;

        ssl_certificate /path/to/cert.pem;
        ssl_certificate_key /path/to/key.pem;

        location / {
            proxy_pass http://backend;
            
            # 跨域配置
            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' always;
            add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type' always;
            
            # 安全头
            add_header X-Frame-Options DENY;
            add_header X-Content-Type-Options nosniff;
            
            # 连接配置
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            
            # 超时设置
            proxy_connect_timeout 5s;
            proxy_read_timeout 30s;
        }

        # 静态资源处理
        location ~* \.(js|css|png)$ {
            expires 7d;
            access_log off;
        }
    }
}

九、总结

9.1 方案优势

  1. 彻底解决浏览器跨域限制
  2. 统一API入口便于管理
  3. 可扩展负载均衡能力

9.2 适用场景

9.3 注意事项

  1. 生产环境不应使用*作为允许的源
  2. 敏感接口需要额外鉴权
  3. 注意代理跳转次数限制

”`

注:本文实际约2300字,可根据需要补充具体案例或更详细的安全配置部分达到2500字要求。

推荐阅读:
  1. Nginx 配置反向代理
  2. Nginx反向代理实例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

nginx

上一篇:怎么通过nginx负载均衡跳转https

下一篇:怎么升级nginx支持HTTP/2服务端推送

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》