Nginx 跨域配置


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1002;
}


http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  on;

	
	
	server {
        listen       8086;
		charset utf-8;

        #后端
        location /ibdti/ {
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Headers *;
            add_header Access-Control-Allow-Methods *;
            proxy_pass http://192.168.3.35:18090/ibdti/;
        }
        
        location / {
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Headers *;
            add_header Access-Control-Allow-Methods *;
            alias html/dist/;
            index  index.html index.htm;
        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }


}

在前后端分离架构中,前端应用和后端 API 通常运行在不同的名或端口上,这会导致 **请求(CORS)** 被浏览器拦截。 为了允许请求,你需要在 **Nginx配置响应头**,告诉浏览器允许访问。 --- ## ✅ Nginx 域配置示例 下面是一个完整的 Nginx 配置示例,用于解决问题: ```nginx server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html; try_files $uri $uri/ =404; } location /api/ { proxy_pass http://java-app:8080/; # 域配置 add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; # 处理预检请求 (OPTIONS) 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_set_header Host $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; } } ``` --- ## 📌 配置解释 ### 1. `add_header` 设置 CORS 相关头信息 | 头部字段 | 说明 | |---------|------| | `Access-Control-Allow-Origin` | 允许的来源(`*` 表示所有) | | `Access-Control-Allow-Methods` | 允许的 HTTP 方法 | | `Access-Control-Allow-Headers` | 允许的请求头 | | `Access-Control-Expose-Headers` | 允许前端访问的响应头 | | `Access-Control-Max-Age` | 预检请求缓存时间(单位:秒) | > ⚠️ `always` 是 Nginx 1.7.5+ 的参数,确保这些头在 204、404 等非 200 响应中也生效。 --- ### 2. `OPTIONS` 请求处理 浏览器在发送请求前会先发送一个 `OPTIONS` 预检请求,确认服务器是否允许操作。 ```nginx 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; } ``` 这段代码确保 `OPTIONS` 请求返回正确的响应头并返回 `204 No Content`。 --- ## ✅ 示例:请求流程 1. 前端地址:`http://localhost:3000` 2. 后端地址:`http://localhost:8080/api/users` 3. 浏览器发起请求,发现,先发送 `OPTIONS` 请求。 4. Nginx 返回 `204` 和正确的 CORS 头。 5. 浏览器允许发送实际请求,Nginx 代理到后端服务。 --- ## 🛠️ 注意事项 - **不要随意使用 `*`**:在生产环境中,建议将 `Access-Control-Allow-Origin` 设置为具体的名(如 `https://your-frontend.com`),而不是 `*`,以提高安全性。 - **`withCredentials` 支持**:如果前端使用了 `credentials: 'include'`,需要设置: ```nginx add_header 'Access-Control-Allow-Credentials' 'true' always; ``` - **避免重复设置头**:如果你的后端已经设置了 CORS 头,Nginx 就不需要再设置,避免冲突。 --- ## ✅ 示例:允许特定 ```nginx add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com' always; ``` --- ## ✅ 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值