简体   繁体   中英

How to redirect http:// http://www and https://www to https:// using .htaccess

I am trying to do a wildcard redirect of http://example.com , http://www.example.com , https://www.example.com to https://example.com

I tried the solution mentioned here but it is not working for me as when i open any page, web browser shows too many redirects error.

The closest I have reached is I can redirect http://example.com and http://www.example.com to https://example.com using following code. But still can't figure out how to do https://www.example.com to https://example.com redirect

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Note (Maybe this is a problem causing too many redirects):
I just noticed that even without specifying any redirect code in .htaccess (see code below), http://www.example.com is getting redirected to http://example.com

<IfModule mod_rewrite.c>

# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Try :

RewriteEngine on
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} ^www
RewriteRule ^.*$ https://example.com%{REQUEST_URI} [R,L]
#wordpress rules

I just figured out the problem. SSL certificate was just created for https://example.com . I assigned a new multi-domain SSL certificate with both example.com and www.example.com and now things are working as expected. Here is my working .htaccess file:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ "https\:\/\/example\.com\/$1" [R=301,L]

RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<IfModule mod_rewrite.c>

# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

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