Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RedirectMatch with HTTP_HOST in the destination

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

like image 200
Tom17 Avatar asked Oct 27 '16 15:10

Tom17


2 Answers

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.

like image 72
Jacob Champion Avatar answered Sep 26 '22 11:09

Jacob Champion


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.

like image 34
ezra-s Avatar answered Sep 22 '22 11:09

ezra-s