简体   繁体   中英

Redirect to https and www with one 301 redirect

all

I want to redirect all requests to land on https://www URL, eg

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!

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM