
我有一個基本的 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
,資產未加載。我也嘗試使用 diff 正規表示式組合重寫規則,但遇到了類似的錯誤。
如何配置 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;
}