由于 mod 重写 htaccess 规则,嵌套 url 出现 500 服务器错误而不是 404

500 Server error instead of 404 on nested urls due to mod rewrite htaccess rule(s)

我有一个带有自定义 .htaccess 文件的站点,它可以处理一些事情:

1) 它将没有“.php”扩展名的 urls 视为末尾有“.php”。

2) 它将 http://http://www. url 重定向到 https://www.

这是 .htaccess 文件:

ErrorDocument 404 /404.php

Options -MultiViews 
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]

一切都按预期工作,但我观察到一些奇怪的行为导致 500 错误而不是 404:

1) 当您访问不存在的根级别 url 时,例如 https://www.example.com/skjdfhkj 它会按预期重定向到 404

2) 当您访问不存在的嵌套 url 例如 https://www.example.com/some-text/skjdfhkj 其中 some-text 不匹配任何现有的 php 文件,那么它 returns 404 符合预期。

3) 然而,当你访问一些不存在的嵌套 url 例如 https://www.example.com/some-existing-page-name/skjdfhkj , where some-existing-page-name matches the name of existing php file (https://www.example.com/some-existing-page-name.php) 时,它会给出一个 500 Server Error

我的问题是:当有人访问不存在的嵌套 url 例如 https://www.example.com/some-existing-page-name/skjdfhkj (where some-existing-page-name matches the name of existing php file (https://www.example.com/some-existing-page-name.php)) ?

我猜它与 mod 重写有关,它把没有 .php 扩展名的 url 当作有 .php,但不知道如何处理mod验证 htaccess 以使其正常工作:(

尝试将最后一条规则更改为:

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

%{REQUEST_FILENAME} 有时会使用部分匹配从文件系统中给出意外匹配。