Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to HTTP non-www to HTTPS www htaccess

Tags:

.htaccess

I want to redirect from any direction to our site with HTTPS protocol, but some redirects it's not working. I want this:

  • http://www.site.co TO https://www.site.co
  • http://site.co TO https://www.site.co

This is my htaccess:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301] 

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

The second rule it's not working. It going to another direction inside our site, and it isn't redirect to HTTPS site.

like image 628
Anibal Mauricio Avatar asked Jul 03 '13 16:07

Anibal Mauricio


People also ask

How do I redirect non-www urls to www?

The easiest way of redirecting a non-www URL to www is to place a rule in the . htaccess file. You can do so via FTP, SSH, or your hosting account's control panel. hPanel users can easily access and edit the .


2 Answers

Try it like this:

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

The only real difference here is that first we redirect from non-WWW to WWW then we check for HTTPS and redirect it.

If it does not work, try this one:

RewriteEngine On  RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]  RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]  
like image 116
Prix Avatar answered Sep 20 '22 04:09

Prix


The answer by Prix works. To make it more dynamic lets use SERVER_NAME and REQUEST_URI instead of a static domain name.

RewriteEngine On
#we replace domain.com/$1 with %{SERVER_NAME}%{REQUEST_URI}.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

#here we dont use www as non www was already redirected to www.
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
like image 41
Alvin Avatar answered Sep 20 '22 04:09

Alvin