The reason http://www.example.com/
is working and https://www.example.com/doesnotexist.html
isn't is because your rewrite condition explicitly disables the rewriting if the client is accessing the site via HTTPS (which I believe several major browsers do by default now, but I don't have a source for this right off the top of my head).
I'm assuming you did that to prevent an infinite loop, which would otherwise infinitely rewrite and redirect every request to (what I assume is) the canonical url, with the client never being able to actually view the page.
I believe the following configuration is what you're looking for. Please note that I tested this on my local server, but I'm running version 2.4.46. As best as I can tell from an admittedly semi-half-assed glance over the version 2.2 mod_rewrite documentation, there weren't any significant changes in the upgrade to version 2.4, at least as it pertains to mod_rewrite
specifically.
RewriteEngine On
RewriteCond expr "! %{REQUEST_URI} -strmatch '/'"
RewriteRule (.*) https://www.example.com/ [L,R=301,NE]
This configuration enables the rewrite engine, obviously, after which it checks the URI of the request. If it's not equal to "/", it rewrites the entire thing to only the document root, issues a 301
redirect like you did in your original, and stops processing any further rules. You may or may not need a RewriteBase "/"
directive declaration right after the RewriteEngine On
. It didn't seem to matter when I tested this, as I was able to rewrite nested-directory URI's with no problem (i.e... /a/b/c
successfully redirected to /
), but the documentation does make a note to point this out, so here I am passing the warning down.
Again, I did test this, but the server version is different so hopefully you don't run into any problems from that. Please note that in order for this to work (barring technical limitations or differences stemming from the aforementioned version difference), your hosting provider needs to have enabled the AllowOverride
directive, probably with the All
option, although I wasn't able to pin down exactly what the minimum requirement for the rewrite directives to work was.