问题
I want to redirect all requests to https and non-www in one jump for main/ home page and other sub pages. I am using the following htaccess. source
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^mytesting\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.mytesting\.com$
RewriteRule .* https://www.mytesting.com%{REQUEST_URI} [R=301,L]
But I got the following redirection
I want like this:
http://mytesting.com > https://mytesting.com
http://www.mytesting.com > https://mytesting.com
http://mytesting.com/faq > https://mytesting.com/faq
https://mytesting.com > https://mytesting.com
http://www.mytesting.com > https://mytesting.com
http://www.mytesting.com/faq > https://mytesting.com/faq
https://mytesting.com/faq > https://mytesting.com/faq
回答1:
You may use this rule for both redirects in one rule:
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]
Here is the explanation of this rule:
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]: ifHOST_NAMEstarts withwww.[NC,OR]: Ignore case match andORs next conditionRewriteCond %{HTTPS} !on:HTTPSis not turned onRewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]: This condition will always match sincewww.is an optional match here. It is used to capture substring ofHTTP_HOSTwithout startingwww.by using(.+)pattern in capture group #1 (to be back-referenced as%1later). Note that(?:..)is a non-capturing group.RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]:^will always match. This rule will redirect tohttps://%1%{REQUEST_URI}withR=301code. Where%1is back-reference of capture group #1 fromRewriteCond, as mentioned above.
来源:https://stackoverflow.com/questions/59399266/how-can-i-redirect-all-requests-to-https-and-non-www-in-one-jump