bhavicp
bhavicp

Reputation: 355

.htaccess HTTP to HTTPS AND non-www to www

I currently have some rules which work for directing http://domain.com to https://www.domain.com, but it doesn't work (I guess it's not matching?) for http://www.domain.com, which should redirect to https://www.domain.com. Could someone modify the below to do this? I've tried quite a few things but haven't been successful, this is my first time with .htaccess rewrite rules.

TL;DR, I need to redirect to both WWW and HTTPS

RewriteEngine On

RewriteRule .? - [E=PROTO:http]

RewriteCond %{HTTPS} =on
RewriteRule .? - [E=PROTO:https]

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

EDIT: I've found the following code, which somewhat works - It redirects both to https://www.domain.com, but it gives a "Too many redirects" error.

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

Upvotes: 1

Views: 835

Answers (2)

ThomasK
ThomasK

Reputation: 2220

This is the rule I'm using:

<IfModule mod_rewrite.c>
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

You could include RewriteCond %{HTTPS} !=on as the first condition to force remove https if that's neccesary...

Hope that helps...

Upvotes: 0

AbsoluteƵER&#216;
AbsoluteƵER&#216;

Reputation: 7880

Have you tried something like this?

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]

It would be better to modify this in the VirtualHost for the server.

NameVirtualHost *:80
 <VirtualHost *:80>
 ServerName www.domain.com
 ServerAlias domain.com
 Redirect permanent / https://www.domain.com/
 </VirtualHost>

 <VirtualHost _default_:443>
 ServerName www.domain.com
 DocumentRoot /www/
 SSLEngine On
 # etc...
</VirtualHost>

Upvotes: 2

Related Questions