问题
I have a site with custom .htaccess file that handles few things:
1) It treats urls without ".php" extensions as if it has ".php" in the end.
2) It redirects http:// and http://www. urls to https://www.
Here is the .htaccess file:
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 ^(.+?)/?$ $1.php [L]
Everything works as expected, but I have observed some strange behavior that resulted in 500 errors instead of 404:
1) When you visit non-existed root level url such as https://www.example.com/skjdfhkj it redirects to 404 as expected.
2) When you visit non-existed nested url such as https://www.example.com/some-text/skjdfhkj where some-text does not match any existing php files, then it returns 404 as expected.
3) However, when you visit some non-existed nested url such as 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), then it gives out a 500 Server Error.
My question is: how do I update my htaccess to properly return a 404 instead of 500 when someone visits non-existing nested url such as 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)) ?
I guess it has something to do with mod rewrite that treats urls without .php extensions as if it had .php, but don't know how to modify htaccess to make it work properly :(
回答1:
Try changing last rule as this:
# if not a directory and .php file is present then add .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
%{REQUEST_FILENAME} sometimes can give unexpected matches from filesystem using partial matches.
来源:https://stackoverflow.com/questions/59364084/500-server-error-instead-of-404-on-nested-urls-due-to-mod-rewrite-htaccess-rule