开发者

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

开发者 https://www.devze.com 2023-04-11 06:00 出处:网络
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:

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 rul开发者_运维知识库e them all!


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.


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]


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号