Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

.htaccess - htaccess redirect for non-www both http and https

I'd like to have:

  • http://example.com redirect to: http://www.example.com
  • https://example.com redirect to: https://www.example.com

And anything that is http://whatever.example.com NOT append the www like http://www.whatever.example.com.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this rule:

RewriteCond %{HTTP_HOST} ^[^.]+.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Here’s an explanation:

  1. The first condition tests if the HTTP header field Host has the required format (contains exactly one period).
  2. The second condition tests if the concatenated value of the value of the HTTPS variable (values on and off) and s (so either ons or offs) is equal to ons and captures the s. This means if %{HTTPS}s evaluates to ons, the first matching group is s and empty otherwise.
  3. The rule will match all requests as every string has a start (marked with ^) and redirects them to the evaluated value of http%1://www.%{HTTP_HOST}%{REQUEST_URI} if both conditions are true. Where %1 is the first matching group of the previous condition (s if HTTPS and empty otherwise), %{HTTP_HOST} is the HTTP Host of the request and %{REQUEST_URI} is the absolute URL path that was requested.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...