Using RedirectMatch with HTTP_HOST in the destination

霸气de小男生 提交于 2020-06-10 18:56:49

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/40289269/using-redirectmatch-with-http-host-in-the-destination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!