nginx location匹配後proxy_pass給後端server後404 一探

tomato發表於2016-12-07

nginx location匹配後proxy_pass給後端server後404 一探

我們先來看如下一段nginx配置

location /zentaopms {
    proxy_pass http://127.0.0.1:8282;
}

location /zentaopms {
    proxy_pass http://127.0.0.1:8282/;
}

server {
   listen 8282;
    root /home/www/zentaopms/www/;
   location ~ .php {
       fastcgi_pass 127.0.0.1:9000;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       include fastcgi_params;
   }
}

如上程式碼中location節點proxy_pass 後相差一個/

我們來看一個具體demo

  • step1-我們要訪問一個URL http://somehost/zentaopms/index.php 這其實是禪道的首頁

  • step2-如我們使用這個配置節

    location /zentaopms {
         proxy_pass http://127.0.0.1:8282;
    }

那麼nginx的錯誤日誌裡面記錄的都是404的錯誤

  • step3-為什麼會發生404

首先location匹配到後將請求代理到後端8282埠的server,代理到8282 server還是原先的url,此時到了8282 的server,8282server去/home/www/zentaopms/www/zentaopms/下找index.php並由fastcgi協議傳送至php中執行,但index.php是在www目錄下,因此nginx就直接報404錯誤

  • step4- / ‘斜槓’
    使用了proxy_pass http://127.0.0.1:8282/;,在最後多了一個/,代表絕對根目錄,nginx不會將location中匹配到的路徑代理走。因此代理到8282 server時,路徑變成了 http://somehost/index.php,這樣子交由server 8282去執行,可以找到php檔案。

author:tomato
qq:385817098
tel:********
job:php程式設計師

相關文章