问题
htaccess to remove the .php extension of my site's files.
RewriteEngine on
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L,QSA]
Now, if I go to my site
www.mysite.com/home
works fine, it redirects to home.php but the URL is still friendly.
But if I write this URL:
www.mysite.com/home.php
The home.php is served, and the URL is not friendly.
How can I avoid this behavior? I want that if the user writes www.mysite.com/home.php, the URL displayed in the URL bar be www.mysite.com/home
回答1:
you can remove .php from requests like so
RewriteCond %{REQUEST_URI} ^/(.*).php$
RewriteRule ^(.*)$ %1 [L,QSA]
回答2:
Code
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]
回答3:
You can also put this code inside of your .htaccess
file:
options +multiviews
What this does is to search for available extensions (.html, .htm and .php I think) inside the current directory. So if for example you request /user
it will look for user.php
.
回答4:
Your rewrite is ignored because it checks for existing file, based on your rule:
RewriteCond %{SCRIPT_FILENAME} !-f
I would suggest adding a URL check in php to redirect to itself (without extension). Or do you want to display 404 error if someone access existing file?
来源:https://stackoverflow.com/questions/9821222/remove-php-extension-explicitly-written-for-friendly-url