User57
User57

Reputation: 2505

Can't redirect to https (htaccess)

I was trying to configure my htaccess file which will redirect from http to https with following lines of statement. But it couldn't .

Note: i don't want the www before the site URL as well.

What could be possible error of my code. Anyone please suggest.

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

Upvotes: 0

Views: 59

Answers (3)

Dusan Bajic
Dusan Bajic

Reputation: 10889

As another solution, if you have only one domain name (www.)example.com, you can use more readable:

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]

Upvotes: 1

anubhava
anubhava

Reputation: 785971

Problem appears to be this line:

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]

This line makes this rule work for domain with starting www only.

You need to make starting www optional by using:

RewriteEngine on

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

Upvotes: 1

Salek Uddin Sheikh
Salek Uddin Sheikh

Reputation: 1

Try the following:

 RewriteEngine On
 RewriteCond %{HTTPS} !=on
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Also, you can also redirect based on port number, for example:

 RewriteCond %{SERVER_PORT} ^80$
 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

This will redirect all requests received on port 80 to HTTPS.

Upvotes: 0

Related Questions