处理前后端跨域

Posted by Ricky Blog on March 26, 2025

要么nginx处理跨域,要么后端处理跨域(如springboot),不要nginx和后端同时处理跨域,会有问题。

nginx 处理跨域
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server {
    listen       80;
    server_name  www.example.com;
    root         /usr/share/nginx/html;
    
    location / {
    
        proxy_pass http://localhost:8188/;
        # 设置是否允许 cookie 传输
        add_header Access-Control-Allow-Credentials true;
        # 允许请求地址跨域 * 做为通配符
        add_header Access-Control-Allow-Origin * always;
        # 允许跨域的请求方法
        add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
        add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

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

https://zahui.fan/posts/lpuzlvhd/