htaccess redirect for non-www both http and https
Asked Answered
C

2

15

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.

Camise answered 6/1, 2010 at 18:12 Comment(0)
S
36

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.
Staal answered 6/1, 2010 at 18:14 Comment(3)
Can you also explain this? It's kind of Chinese for me... the first line is for catching only 2-part host (like: example.com). What the second line does, and how?Roop
Looks good, but is producing 500 internal error message for me.Rebutter
On some hosts you will need to replace the second line with RewriteCond %{HTTP:X-Forwarded-SSL}s ^on(s)| for proper SSL detection.Roentgenoscope
A
2

Try adding this RewriteCond to your .htaccess file to catch SSL only - then do the same thing for standard http.

RewriteCond %{HTTPS} on
Archduchy answered 6/1, 2010 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.