.htaccess hide extension while forcing www
I have t开发者_StackOverflowhe following htaccess file, which hides the php extension and forces all URLs to use www:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</IfModule>
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
For the first part the credit goes to this answer and the second one to this answer.
This works perfect in most cases, however there is one problem. When a user tries to go to http://example.com/foo (or instead of "foo", whatever other page) it redirects to http://www.example.com/foo.php .
How can I make it redirect to http://www.example.com/foo , that is, whithout the .php?
You just need to change the order of your rules. First external redirect then the internal one. Have your code like this:
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</IfModule>
I have tested it and works fine on my end.
What is "foo" in this case, a file? If so, this works:
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
If you want to exclude "foo" specifically,
RewriteRule ^foo$ - [L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
If you're trying to use a web framework, then they probably want you to redirect all non-file and non-directory requests to something like index.php.
Edit: Try swapping and consolidating the two sections:
Options +FollowSymLinks
Options +Indexes
<IfModule rewrite_module>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</IfModule>
精彩评论