返回 500 Internal Server Error 而不是:404 - Not Found

500 Internal Server Error returned instead of: 404 - Not Found

我收到 500 Internal Server Error 而不是:404 - Not Found 每当我为我的站点键入不存在的页面地址时。

我猜这与我的 .htaccess 设置有关:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.example.com/ [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/ [L,R=301] 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$  [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ .php [L,QSA] 

ErrorDocument 404 /404.php

我的 .htaccess 检查并将所有 url 重定向到 https://www. 形式。它还负责隐藏所有页面的 .php 扩展名。

我花了很长时间才想出上面的代码,现在我真的不敢更改任何东西,因为我不太擅长 .htaccess 语法。

如有任何帮助或建议,我们将不胜感激!

在这些拖线之后:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

添加这一行:

RewriteCond %{REQUEST_FILENAME}\.php -f

确保请求在发送之前接受 php 扩展名:

RewriteRule ^(.*)$ .php [L,QSA] 

当您向任何目标发送不存在的请求时,请确保目标将正确处理此问题,否则服务器将给出错误。

  1. 您的 2 条重定向规则必须合并为一条以避免多次 301 重定向(不利于 SEO 和效率)
  2. 在您的 URI 中添加 .php 之前,您必须检查是否存在 .php 文件。
  3. 避免在您的规则中对主机名进行硬编码。

完整的.htaccess:

ErrorDocument 404 /404.php

RewriteEngine On

## add www and turn on https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

# if not a directory and .php file is present then add .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ .php [L]