Redirect to https and www in single redirect in Ap

2019-07-29 12:06发布

问题:

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

回答1:

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]