I'm having a hard time figuring out how to properly configure a mod_rewrite rule for the following conditions:
- redirect non-www to www AND http to https ONLY for the root path: / ie. example.com
- disregard anything else such as /test.html ie. example.com/test.html
Note that I'm writing the rules in Apache include files within directory rules.
Here's what I'm currently using:
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This correctly redirects all non-www requests to www, but it also allows for HTTP requests, which I'd like to prevent but only for / ie. example.com
Then I tried the following:
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^$ https://www.example.com [L,R=301]
This (apparently) worked, but it turned out it blocked all 3rd party uptime-monitoring sites from issuing HTTPS get requests, even though it was working fine in a regular browser. So I'm out of ideas.
example.com
(no www) then yes, the "redirect" might effectively "block" the monitoring site. Or, you could implement an exception, although that should be unnecessary I would have thought. Your second rule block should be OK. (Your first rule block specifically maintains the protocol on the original request - which is not what you require.)www
"redirect", because the incorrect hostname is being monitored, then you should modify the URL being monitored, not include an exception in your current rule block. As Sum1sAdmin hinted at, if these directives are in your server-config then they can probably be simplified (depending on how you have configured your VirtualHosts, and exactly where these directives are being included). For example, a singleRedirectMatch
directive might be all that's required.