.htaccess 将对文件名 URL 的请求重写为相应的永久链接 URL

.htaccess rewrite requests for file-name URLs to corresponding permalink URLs

我对我的 .htaccess 代码有疑问。它正在执行以下操作:

  1. 为每个 URL
  2. 添加尾部斜线
  3. 删除 .php 文件扩展名。

这行得通,所以如果我键入 domain.com/page/,浏览器会显示 domain.com/page.php 的内容。如果我键入 domain.com/page(没有尾部斜杠),浏览器将重定向到 domain.com/page/.

BUT 如果我输入 domain.com/page.php 浏览器会 not 重定向到 domain.com/page/.

有没有办法将请求 domain.com/page.php 重定向到 domain.com/page/

这是我当前的 .htaccess 代码:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !(^$|\.[a-zA-Z0-9]{1,5}|/)$ %{REQUEST_URI}/ [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^((/?[^/]+){1,2})/$ .php [L]

感谢您的帮助!

根据您展示的示例,请您尝试以下操作。 请确保在测试您的 URL 之前清除您的浏览器缓存。

RewriteEngine ON
##First 2 rules are added by OP itself.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !(^$|\.[a-zA-Z0-9]{1,5}|/)$ %{REQUEST_URI}/ [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^((/?[^/]+){1,2})/$ .php [L]

##Newly added rule for removing .php from browser if .php is hit in it.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ .php [NC,L]