1

I want to redirect following domains

http://example.com
http://www.example.com
https://example.com

to

https://www.example.com

in a single http request

I know it can be done in two requests using

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

but and extra redirect increases loadtime of page.

I want to do both things in one http request

I am using apache2 on ubuntu

Thanks in advance

Eirtaza
  • 137
  • 2
  • 16

1 Answers1

3

To redirect to https and www in a single http request, you can use

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • 1
    working flawlessly... have to add these lines both to secure and normal vhost config – Eirtaza Aug 11 '16 at 19:39
  • @amit-verma how would I do the same if the site works on `https://example.com`? – bugnumber9 Dec 05 '20 at 10:39
  • 1
    @bugnumber see my answer on this post https://stackoverflow.com/questions/1478173/htaccess-redirect-www-to-non-www-with-ssl-https/42653862#42653862 – Amit Verma Dec 05 '20 at 11:48