1. 資源路徑問題
Web 頁面中的靜態資源(如圖片、CSS、JavaScript 文件)可能使用了相對路徑或絕對路徑,而這些路徑在代理后無法正確加載。
解決方法:
-
檢查資源路徑:打開瀏覽器的開發者工具(按?
F12
),查看哪些資源加載失敗。通常這些資源的 URL 可能是錯誤的。 -
修正資源路徑:
-
如果資源路徑是相對的(如?
./css/style.css
),確保它們在代理后的上下文中仍然有效。 -
如果資源路徑是絕對的(如?
/css/style.css
),需要在 Nginx 配置中正確處理路徑。
-
示例:
假設 Web 頁面的資源路徑是?/static/css/style.css
,而你通過 Nginx 代理訪問的是?/login
,那么資源路徑可能會被解析為?/login/static/css/style.css
,導致加載失敗。
可以通過以下方式修正:
location /static/ {proxy_pass http://原始服務器IP:端口/static/;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
2.?Host
?頭問題
Nginx 默認會將?Host
?頭設置為代理服務器的地址( 代理服務器IP),而不是原始服務器的地址(原始服務器IP:端口)。這可能導致后端服務器無法正確處理請求。
解決方法:
在 Nginx 配置中,顯式設置?Host
?頭為原始服務器的地址:
location /login {proxy_pass http://原始服務器IP:端口;proxy_set_header Host $host; # 或者直接設置為后端服務器的地址proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
3. 靜態資源未正確代理
如果靜態資源(如圖片、CSS、JavaScript)沒有被正確代理到后端服務器,它們將無法加載。
解決方法:
確保 Nginx 配置中代理了所有必要的路徑。例如:
location / {proxy_pass http://原始服務器IP:端口;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }location /static/ {proxy_pass http://原始服務器IP:端口/static/;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
4. 跨域問題
如果 Web 頁面中的某些資源是通過 JavaScript 動態加載的(例如通過 AJAX 請求),可能會遇到跨域問題。
解決方法:
在 Nginx 配置中添加跨域支持:
location / {proxy_pass http://原始服務器IP:端口;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;# 允許跨域add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; }
5. 緩存問題
瀏覽器可能緩存了舊的資源文件,導致頁面顯示不正確。
解決方法:
-
清除瀏覽器緩存,然后重新加載頁面。
-
在 Nginx 配置中禁用緩存:
location / {proxy_pass http://原始服務器IP:端口;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;# 禁用緩存add_header Cache-Control 'no-cache, no-store, must-revalidate';add_header Pragma 'no-cache';add_header Expires '0'; }
總結
通過以下步驟排查和解決問題:
-
使用瀏覽器的開發者工具檢查哪些資源加載失敗。
-
確保 Nginx 正確代理了所有必要的路徑。
-
確保?
Host
?頭設置正確。 -
處理跨域問題(如果涉及)。
-
清除瀏覽器緩存或禁用緩存。
-
檢查后端服務器日志。
案例:
events {worker_connections 1024;
}http {upstream tomcat_cluster {server 本地IP:8080;server 本地IP:8081;}server {listen 80;server_name localhost;# 代理到本地 Tomcat 集群location / {proxy_pass http://tomcat_cluster;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}# 代理到外部 URLlocation /login {proxy_pass http://原始服務器IP:端口/后綴;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}}
}