我尝试使用nginx为nodejs应用程序设置反向代理。我的节点应用程序当前在example.com服务器的端口8005上运行。运行应用程序并转到example.com:8005,应用程序运行完美。但是当我尝试设置nginx时,我的应用程序似乎首先通过访问example.com/test/工作但是当我尝试发布或获取请求时,请求想要使用example.com:8005 url并且我最终得到一个交叉起源错误,CORS。我想请求网址反映nginx网址,但我没有运气到那里。下面是我的nginx default.conf文件。
server {
listen 80;
server_name example;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location /test/ {
proxy_pass http://localhost:8005/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
答案 0 :(得分:1)
必须有一些方法可以告诉nginx你正在使用哪个应用程序。
所以为此,要么你可以在所有的apis前加上说测试(location /test/api_uri
),然后抓住所有带有前缀/ test的url和proxy_pass将它们带到节点,或者如果你的urk中有一些特定的模式,你可以用正则表达式捕获该模式,比如假设,所有app1 apis都包含app1,然后使用location ~ /.*app1.* {} location ~ /.*app2.*
捕获这些url,确保你保留order的位置。
演示代码:
server {
...
location /test {
proxy_pass http://localhost:8005/; #app1
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /test2 {
proxy_pass http://localhost:8006/; #app2
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
...
}
正则表达式的其他演示,
server {
...
location ~ /.*app1.* {
proxy_pass http://localhost:8005/; #app1
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ /.*app2.* {
proxy_pass http://localhost:8006/; #app2
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
...
}