Nginx

無法為帶有永久連結和 nginx 的 Wordpress 頁面獲取 404

  • May 30, 2018

我有 nginx 1.6.2 為 wordpress 站點提供服務,帶有 php-fpm。

永久連結按以下方式設置:/blog/%postname%/

nginx 正確地服務於站點頁面(/, /products, /contact…)以及部落格文章(在 下/blog/)。404 非常適合部落格文章(即example.com/blog/idontExist會以 404 響應)。但是,瀏覽example.com/iDontExist獲取 HTTP 200 響應和站點索引頁面的內容,而不是 404。

這是我的 nginx.conf:

server {
   server_name example.com;

   root /var/local/example.com/;

   access_log /var/log/nginx/example.com-access.log main;
   error_log  /var/log/nginx/example.com-error.log;

   error_page 404 /index.php?$request_uri;

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

       fastcgi_split_path_info ^(.+\.php)(/.+)$;
       # fastcgi_split_path_info ^(/blog)(/.*)$;
       include /etc/nginx/fastcgi_params;
       #fastcgi_intercept_errors on;
       #fastcgi_param  PATH_TRANSLATED         $document_root$fastcgi_path_info;
       fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
       fastcgi_pass unix:/var/run/php5-fpm.sock;
       fastcgi_index /index.php;

   }

   location / {
       auth_basic           "private section";
       auth_basic_user_file /var/local/example.com/conf/.htpasswd;
       try_files $uri $uri/ /index.php?$args;
   }

   location ~ /\.ht {
       deny  all;
   }
}

這是我的 fastcgi_params:

fastcgi_param  QUERY_STRING   $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE   $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI   $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# bug workaround : http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

我已經根據論壇上的內容閱讀並嘗試了許多變體,但沒有任何效果。

原來通過編輯 php.ini 解決了這個問題:

cgi.fix_pathinfo=0

取而代之

cgi.fix_pathinfo=1

然後重新載入 php-fpm 守護程序。

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