# nginx - 反向代理及Cookie
# 转发所有请求
server {
listen 9001;
location /api {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
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 Cookie $http_cookie; # 设置cookie
proxy_pass http://api.server/; # 代理的服务器地址
proxy_cookie_domain domino.server nginx.server;
proxy_redirect off;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# proxy_pass
代理转发主要通过 proxy_pass
配置, 如果在 proxy_pass
后面的 url
加 /
,表示绝对根路径,不会带上匹配到的路径;如果没有 /
,表示相对路径,把匹配的路径部分也代理。
配置栗子🌰:
针对以下配置,使用 http://localhost/proxy/test.html 进行访问
- 第一种:
location /proxy/ {
proxy_pass http://127.0.0.1:4000/;
}
1
2
3
2
3
会被代理到 http://127.0.0.1:4000/test.html
- 第二种:
相对于第一种,最后少一个
/
location /proxy/ {
proxy_pass http://127.0.0.1:4000;
}
1
2
3
2
3
会被代理到 http://127.0.0.1:4000/proxy/test.html
- 第三种:
location /proxy/ {
proxy_pass http://127.0.0.1:4000/api/;
}
1
2
3
2
3
会被代理到 http://127.0.0.1:4000/api/test.html
- 第四种:
相对于第三种,最后少一个
/
location /proxy/ {
proxy_pass http://127.0.0.1:4000/api;
}
1
2
3
2
3
会被代理到 http://127.0.0.1:4000/apitest.html