删除友好URL的.php扩展名(明确写入)

时间:2012-03-22 11:17:22

标签: php .htaccess mod-rewrite friendly-url

htaccess删除我网站文件的.php扩展名。

RewriteEngine on
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L,QSA]

现在,如果我去我的网站

www.mysite.com/home

工作正常,它重定向到home.php但URL仍然是友好的。

但如果我写这个网址:

www.mysite.com/home.php

提供了home.php,网址不友好。

我该如何避免这种行为?我希望如果用户写www.mysite.com/home.php,则URL栏中显示的URL为www.mysite.com/home

4 个答案:

答案 0 :(得分:10)

代码

RewriteEngine On
RewriteBase /

# remove enter code here.php; use THE_REQUEST to prevent infinite loops
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]


# remove index
RewriteRule (.*)/index$ $1/ [R=301]

# remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]

# add .php to access file, but don't redirect
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

答案 1 :(得分:5)

你可以从像这样的请求中删除.php

RewriteCond %{REQUEST_URI} ^/(.*).php$
RewriteRule ^(.*)$ %1 [L,QSA]

答案 2 :(得分:5)

您也可以将此代码放在.htaccess文件中:

options +multiviews

这样做是为了在当前目录中搜索可用的扩展名(.html,.htm和.php)。因此,如果您要求/user,则会查找user.php

答案 3 :(得分:0)

您的重写被忽略,因为它会根据您的规则检查现有文件:

RewriteCond %{SCRIPT_FILENAME} !-f

我建议在php中添加一个URL检查以重定向到自己(没有扩展名)。或者,如果有人访问现有文件,您是否要显示404错误?