我有一个正在运行的基本 nginx 代理http://127.0.0.1:8080
。
这是nginx.conf
:
events {}
http {
server {
listen 8080;
server_name 127.0.0.1;
rewrite_log on;
error_log /var/log/nginx/error.log notice;
location / {
proxy_pass http://127.0.0.1:5200;
proxy_set_header Host 127.0.0.1:5200;
}
location /api {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host 127.0.0.1:8000;
}
location = /app2 {
return 302 /app2/;
}
location /app2/ {
proxy_pass http://127.0.0.1:5300/;
proxy_set_header Host 127.0.0.1:5300;
}
}
}
点击 时http://127.0.0.1:8080/app2
,会显示在端口上运行的应用程序5300
,但资产未正确加载。我怀疑 nginx 正在将资产请求代理到在端口上运行的另一个应用程序5200
,即location /
。我停止了这个应用程序进行确认,这是来自 nginx 的日志(请注意,上游显示为 ,http://127.0.0.1:5200...
但应该是http://127.0.0.1:5300...
)
2023/09/17 23:47:32 [error] 29#29: *10 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: 127.0.0.1, request: "GET /assets/css/fonts/Pe-Icon-Stroke/Pe-icon-7-stroke..ttf?d7yf1v HTTP/1.1", upstream: "http://127.0.0.1:5200/assets/css/fonts/Pe-Icon-Stroke/Pe-icon-7-stroke..ttf?d7yf1v", host: "127.0.0.1:8080", referrer: "http://127.0.0.1:8080/app2/"
127.0.0.1 - - [17/Sep/2023:23:47:32 +0000] "GET /assets/css/fonts/Pe-Icon-Stroke/Pe-icon-7-stroke..ttf?d7yf1v HTTP/1.1" 502 559 "http://127.0.0.1:8080/app2/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
2023/09/17 23:47:32 [error] 29#29: *10 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: 127.0.0.1, request: "GET /assets/css/fonts/Font-Awesome/fontawesome-webfont..ttf?v=4.7.0 HTTP/1.1", upstream: "http://127.0.0.1:5200/assets/css/fonts/Font-Awesome/fontawesome-webfont..ttf?v=4.7.0", host: "127.0.0.1:8080", referrer: "http://127.0.0.1:8080/app2/"
127.0.0.1 - - [17/Sep/2023:23:47:32 +0000] "GET /assets/css/fonts/Font-Awesome/fontawesome-webfont..ttf?v=4.7.0 HTTP/1.1" 502 559 "http://127.0.0.1:8080/app2/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
我看到类似的问题http://127.0.0.1:8080/api
,资产未加载。我也尝试使用不同的正则表达式组合重写规则,但得到了类似的错误。
如何配置 nginx 以路由到不同的应用程序并正确加载其资产。
答案1
经过进一步的挖掘和测试,rewrite
解决方案详述于https://stackoverflow.com/questions/62836801/nginx-reverse-proxy-how-to-serve-multiple-apps对我来说是有效的。
这是我添加到 nginx.conf 中的代码片段,用于正确加载 app2 的资产
if ($http_referer ~ https?://[^/]+/app2/(.*))
{
# rewrite request URI only if it isn't already started with '/app2' prefix
rewrite ^((?!/app2).*) /app2$1;
}