How to always remove WWW from a url with mod_rewrite?

后端 未结 5 807
无人共我
无人共我 2020-12-24 09:21

I\'m using the following to try and remove WWW from the url:

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://example.com$1 [R=301]


        
相关标签:
5条回答
  • 2020-12-24 09:57

    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>
    
    0 讨论(0)
  • 2020-12-24 09:59

    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.

    0 讨论(0)
  • 2020-12-24 10:06

    Here’s a more generalized solution:

    RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]
    
    0 讨论(0)
  • 2020-12-24 10:13

    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.

    0 讨论(0)
  • 2020-12-24 10:15

    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
    
    0 讨论(0)
提交回复
热议问题