1. 程式人生 > 實用技巧 >nginx try_files引起500錯誤的解決過程

nginx try_files引起500錯誤的解決過程

Nginx 500錯誤(Internal Server Error內部伺服器錯誤):500錯誤指的是伺服器內部錯誤,也就是說伺服器遇到意外情況,而無法履行請求。


最近在更新版本時,發現Nginx error日誌不停在列印rewrite or internal redirection cycle while internally redirecting to..,但是伺服器又存在這些靜態檔案,以下是分析步驟:

1.檢視報錯日誌

2019/08/16 00:42:01 [error] 1801#1801: *60690 rewrite or internal redirection cycle while internally redirecting to "/tcoinShop-h5/credit_h5/index.html", client: 100.12
0.34.90, server: tcoin.trc.com, request: "GET /credit_h5/static/js/1.bddd748718eee4b77012.js HTTP/1.1", host: "tcoin.trc.com", referrer: "https://tcoin.trc.com/credit_h5/"

發現是很多請求/credit_h5/static/js/1.bddd748718eee4b77012.js時的報錯,由https://tcoin.trc.com/credit_h5/請求;

2.檢視該檔案是否存在
去伺服器上查詢該檔案並不存在,但是請求的就是這個地址;

3.reload nginx
懷疑是nginx配置檔案沒有生效,重新reload的一遍,發現該現象仍然存在;

4.ping 域名

[root@MI ~]# ping tcoin.trc.com
PING tcoin.trc.com.m.alikunlun.com (122.228.234.240) 56(84) bytes of data.
^C64 bytes from 122.228.234.240: icmp_seq=1 ttl=56 time=7.75 ms

--- tcoin.trc.com.m.alikunlun.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 7.750/7.750/7.750/0.000 ms

發現該域名過了CDN,然後懷疑是CDN快取的問題,清理一下CDN的快取;

5.錯誤日誌變得很少了,還是會有error進來,懷疑是客戶端app存在本地快取,告知使用者清理快取;

6.問題解決;

故障原因:
在nginx配置檔案中使用了try_files,如果平時不會出問題,但是由於更新存在快取的問題,導致部分使用者還是會去載入老的靜態檔案,導致服務端500錯誤。

try_files

    location ~.*\.(gif|jpg|jpeg|png)$ {
        root /web/wwwroot;
        try_files /static/$uri $uri;
    }

意思為當你去訪問http://abc.com/test.jpg

時,會去先檢查/web/wwwroot/static/test.jpg是否存在,不存在就讀取/web/wwwroot/test.jpg,但是由於最後一個引數時內部重定向,所以並不會去檢查/web/wwwroot/test.jpg是否存在,只要第一個路徑不存在就會重定向,然後再進入到這個location造成死迴圈。結果出現500 Internal Server Error