I keep reading that, where possible, I should not be using mod_rewrite
. As such, I am trying to do a http to https rewrite with RedirectMatch.
Question: How can I use RedirectMatch
and use Apache server variables (such as %{HTTP_HOST}
) in the URL parameter?
This code fails to return a response to the client (Chrome):
RedirectMatch ^(.*) https://%{HTTP_HOST}/$1
I recently asked a similar question to this, but it may have been too wordy and lacks direction for an answer: Redirecting http traffic to https in Apache without using mod_rewrite
If you're using 2.4.19 or later, the Redirect
directive has a somewhat obscure feature: putting it inside a Location
or LocationMatch
will enable expression syntax.
So your example can be written as
<LocationMatch ^(?<PATH>.*)>
Redirect "https://%{HTTP_HOST}%{env:MATCH_PATH}"
</LocationMatch>
(Here, the ?<PATH>
notation means that the match capture will be saved to an environment variable with the name MATCH_PATH
. That's how we can use it later in the Redirect
.)
It's even easier if you always redirect using the entire request path, because you can replace the capture group entirely with the REQUEST_URI
variable:
<Location "/">
Redirect "https://%{HTTP_HOST}%{REQUEST_URI}"
</Location>
Now, is this easier to maintain/understand than just using mod_rewrite for this one case? Maybe not. But it's an option.
No, You can't use variables of that type with Redirect/RedirectMatch. If you need variables, such as %{HTTP_HOST}
, use mod_rewrite.
Note: I commend you for not trying to use mod_rewrite right away, because most people will go for mod_rewrite even for the simplest of redirections, which is clearly overkill and most times it is just looking to complicate things unnecessarily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With