I'm using the following to try and remove WWW from the url:
RewriteC开发者_如何学Pythonond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://example.com$1 [R=301]
But for some reason it doesn't work. Any suggestions?
Here’s a more generalized solution:
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]
Try:
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
And without mod_rewrite
:
<VirtualHost 10.0.0.1:80>
ServerName www.example.com
Redirect permanent / http://example.com/
</VirtualHost>
Virtual hosts can be used by completing the steps in the following URL: Setting Up A Virtual Host in Apache.
As a minor tweak of Kyle's answer, I'd put a / in the RewriteRule match condition, like
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^/(.*)$ http://example.com/$1 [R=301,L]
Otherwise, you get a double slash as a result.
http://www.example.com/smth -> http://example.com//smth
I would always use 307 (temporary redirect) first because if you get it wrong some browsers cache it permanently. I ended up installing Google Chrome just because I couldn't get my Firefox to forget a bad redirect even when I deleted the whole cache.
Here is a solution if you don't want a hard coded domain name. Don't forget to start the rewrite engine or this won't work!
# Start rewrite engine
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
</IfModule>
# Rewrite "www.example.com -> example.com"
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
精彩评论