【发布时间】:2020-04-09 08:33:56
【问题描述】:
我有一个带有自定义 .htaccess 文件的网站,它处理的事情很少:
1) 它将没有“.php”扩展名的 url 视为最后有“.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 ^(.+?)/?$ $1.php [L]
一切正常,但我观察到一些奇怪的行为导致 500 错误而不是 404:
1) 当您访问不存在的根级 URL(例如 https://www.example.com/skjdfhkj)时,它会按预期重定向到 404。
2) 当您访问不存在的嵌套 url 例如 https://www.example.com/some-text/skjdfhkj 其中some-text 不匹配任何现有的 php 文件时,它会按预期返回 404。
3) 但是,当您访问一些不存在的嵌套 url,例如 https://www.example.com/some-existing-page-name/skjdfhkj 时,其中 some-existing-page-name 匹配现有 php 文件的名称 (https://www.example.com/some-existing-page-name.php),然后它会给出一个 500 Server Error。
我的问题是:我如何更新我的 htaccess 以正确返回 404 而不是 500 当有人访问不存在的嵌套 url 例如 https://www.example.com/some-existing-page-name/skjdfhkj (其中 some-existing-page-name 匹配现有 php 文件的名称(https://www.example.com/some-existing-page-name.php)) ?
我想这与 mod rewrite 有关,它将没有 .php 扩展名的 url 视为具有 .php,但不知道如何修改 htaccess 以使其正常工作:(
【问题讨论】:
标签: php .htaccess mod-rewrite http-status-code-404