Eirtaza Eirtaza - 1 year ago 85
HTTP Question

Redirect to https and www in single redirect in Apache

I want to redirect following domains




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

Answer Source

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]