Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http to https redirect along with www to non-www in htaccess

I'm trying to redirect my site from http to https and from www to non-www at the same time. This code from Andron here works but with a few glitches. I've slightly tweaked it and redirected everything from the non-https to https as well.

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

For the following situations the redirect works flawlessly and redirects to the non-www https version:

domain.com
www.domain.com
www.domain.com/page

However, when I enter the domain.com/page or http://domain.com/page I see only the non-secure http non-www version.

How do I make sure that all URLs redirect to the secure https non-www version of the site?

like image 988
hpb Avatar asked Feb 04 '26 21:02

hpb


1 Answers

Here is a rule that does both http->https and www removal in single rule:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

Multiple redirects should better be avoided for SEO purpose.

like image 118
anubhava Avatar answered Feb 06 '26 13:02

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!