Apache-2.2

Nginx 404 頁面行為

  • July 25, 2012

我有以下 nginx 伺服器配置:

server {
   listen 80;
   server_name example.com
   root   /server/root;

   index index.php;

   error_page 404 = /index.php;

   location ~ \.php$ {
       try_files $uri =404;

       proxy_pass         http://127.0.0.1:8080;
       proxy_redirect     off;
       proxy_set_header   Host $host;
       proxy_set_header   X-Real-IP        $remote_addr;
       proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
       proxy_set_header   X-Request-URI    $request_uri;
   }

}

我想要的行為是,當 nginx 遇到對不存在文件的請求時,它會通過 404 頁面顯示 index.php 頁面。問題是 apache(這是被代理返回的)似乎仍在嘗試在收到請求時解決原始請求。如果我去http://example.com/blahblah,我會得到錯誤:

The requested URL /blahblah was not found on this server.

這是一個apache錯誤。如何使 index.php 顯示為 404 頁面,就像它是靜態文件一樣?

你用的是哪個版本的 nginx?此問題已在 1.1.12 中解決:http: //nginx.org/en/CHANGES

編輯:如果您無法更新,您可以將目前的 error_page 和 try_files 替換為:

location / {
 try_files $uri $uri /index.php;
}

location ~ \.php$ {
 # Leave the =404 at the end so we don't 500 when /index.php doesn't exist
 try_files $uri /index.php =404;

 proxy_pass         http://127.0.0.1:8080;
 proxy_redirect     off;
 proxy_set_header   Host $host;
 proxy_set_header   X-Real-IP        $remote_addr;
 proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
 proxy_set_header   X-Request-URI    $request_uri;
}

引用自:https://serverfault.com/questions/411111