3

all

I want to redirect all requests to land on https://www URL, e.g.

case1: http://www.example.com --301--> https://www.example.com
case2: https://example.com    --301--> https://www.example.com
case3: http://example.com     --301--> https://www.example.com

Here I have my code in .htaccess file

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

It works fine in case 1 and 2. However when I have a http and non-www request (case3), it will require two 301 redirects to land on https://www

http://example.com 
--301--> 
https://example.com 
--301--> 
https://www.example.com

How can we force https and www with always just 1 301 redirect.

I am not very familiar with Apache and rewrite module. Help please!

Jerry
  • 81
  • 8

1 Answers1

3

To redirect to https://www in a single request, you can use :

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
 RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • Can you also help me with if you want to redirect all requests to https but non-www? – Jerry Apr 18 '17 at 04:22
  • @Jerry you can modify the Code , remove the **!** from the RewriteCondition and Remove the **www** from Rewrite destination (last line) . – Amit Verma Apr 18 '17 at 04:30