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

miq*_*uel 4 php .htaccess mod-rewrite friendly-url

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

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

现在,如果我去我的网站

www.mysite.com/home
Run Code Online (Sandbox Code Playgroud)

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

但是,如果我写这个URL:

www.mysite.com/home.php
Run Code Online (Sandbox Code Playgroud)

提供home.php,URL不友好.

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

小智 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]
Run Code Online (Sandbox Code Playgroud)


sci*_*uff 5

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

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


Sor*_*anu 5

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

options +multiviews
Run Code Online (Sandbox Code Playgroud)

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