。htaccess删除PHP扩展名与重定向尾部斜杠

问题描述 投票:0回答:1

我有三段代码。

这是第一个:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

第二个:

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R,NE]

第三个:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-_]+)/$ profile/index.php?username=$1 [QSA,L]
  1. 第一个从URL栏中删除.php扩展名
  2. 第三部分显示目录的内容。例如,example.com/billgates/显示以下页面的内容:example.com/profile/index.php?username=billgates
  3. [第二个添加斜线并重定向#2的非斜线。例如,example.com/billgates重定向到example.com/billgates/

所有代码都可以工作,但不能很好地结合在一起。这是问题所在:

如果我转到example.com/login,它将删除.php扩展名,并且可以正常工作。但是问题是,如果我在/login/的末尾手动添加了一个斜杠,它会重定向到:example.com/login/.php/,但它应该将我重定向到/login,因为它不是目录,而只是一个页面。但是,如果/login/是目录,则不应重定向。


完整的.htaccess:

RewriteEngine On

ErrorDocument 404 /404.php

...the three pieces of codes above
php .htaccess mod-rewrite url-rewriting
1个回答
1
投票

具有这种方法,请在清除浏览器缓存后进行测试:

ErrorDocument 404 /404.php

RewriteEngine On

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule /$ - [L,R=404]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)$ $1.php [L]


RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/$ profile/index.php?username=$1 [QSA,L]
© www.soinside.com 2019 - 2024. All rights reserved.