Nginx 在同一个路径下反代 HTTP 和 WebSocket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
server {
// settings

location /api/ {
try_files /nonexistent @$http_upgrade;
}
location @ {
rewrite ^/api/(.*) /$1 break;
proxy_pass http://127.0.0.1:4080;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-PORT $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location @websocket {
rewrite ^/api/(.*) /$1 break;
proxy_pass http://127.0.0.1:4080;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-PORT $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# websocket
proxy_http_version 1.1;
proxy_set_header Connection "Upgrade";
proxy_set_header Upgrade $http_upgrade;
}
}