how can I Redirect all requests to https and non-www in one jump?

旧时模样 提交于 2020-01-15 10:16:09

问题


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]: if HOST_NAME starts with www.
  • [NC,OR]: Ignore case match and ORs next condition
  • RewriteCond %{HTTPS} !on: HTTPS is not turned on
  • RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]: This condition will always match since www. is an optional match here. It is used to capture substring of HTTP_HOST without starting www. by using (.+) pattern in capture group #1 (to be back-referenced as %1 later). Note that (?:..) is a non-capturing group.
  • RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]: ^ will always match. This rule will redirect to https://%1%{REQUEST_URI} with R=301 code. Where %1 is back-reference of capture group #1 from RewriteCond, as mentioned above.


来源:https://stackoverflow.com/questions/59399266/how-can-i-redirect-all-requests-to-https-and-non-www-in-one-jump

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!