Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Yet another) Beautiful way to remove www via rewrite in .htaccess?

Yes, I know this question has been asked 1000 times before... here is the difference...

I found this answer on StackOverflow to ADD the "www" here: use htaccess to add www with https support

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

And it is the most beautiful and graceful solution I have ever seen:

  • It works
  • It doesn't need to be changed to be used for a specific domain
  • It addresses both HTTP and HTTPS connections
  • Its only 3 lines

So, my question is simple. Can someone help me adapt this code to work in the opposite direction? (To remove the WWW from web addresses and address all the above points)?

I believe that between the above (and hopefully below) solutions, we will have the www rewrite to rule them all!

like image 743
ethanpil Avatar asked Oct 06 '11 00:10

ethanpil


3 Answers

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%2://%1%{REQUEST_URI} [L,R=301]

Taken from the Drupal 7 .htaccess file, works like a charm. Updated a bit to add the https check.

like image 188
Clive Avatar answered Oct 29 '22 15:10

Clive


I got problem with above answer, it started to redirect to http://http:///

So I did some changes and this is code which worked for me (on apache2 Ubuntu server, VPS server) to redirect from http://www.example.com to http://example.com (www to non www) AND from http://example.com to https://example.com (http to https).

    RewriteCond %{HTTPS}s on(s)|
    RewriteCond %{HTTP_HOST} ^www\.(.+)$
    RewriteRule ^ http%2://%1%{REQUEST_URI} [R=301,L]
like image 28
Makarand Mane Avatar answered Oct 29 '22 16:10

Makarand Mane


Here's a version that is only two lines, and works on both Apache and LiteSpeed

RewriteCond %{HTTPS}s-%{HTTP_HOST} ^(on(s)|offs)-www\.(.+)$ [NC]
RewriteRule ^(.*)$ http%2://%3/$1 [L,R=301]
like image 36
Victoria Avatar answered Oct 29 '22 14:10

Victoria