Home > Net >  Using mod_rewrite to redirect based on query string parameter
Using mod_rewrite to redirect based on query string parameter

Time:12-02

I am trying to get something working with mod_rewrite, but am not entirely sure it's even possible.

Say I have some request like:

https://www.example.com?h=somerandomvalue&u=www.another.example/content

I'd like to take the value of the u parameter and rewrite the request using this value, so from the above example request, I'd like to rewrite it to be

https://www.another.example/content

So basically, request:

https://www.example.com?h=somerandomvalue&u=www.another.example/content

Redirects to:

www.another.example/content

Is this possible? I've seen other examples where people are capturing and using parameters as part of a rewritten path but I have not seen anything in the way of redirecting to an entirely new domain using the provided parameter.

Any help or guidance here is very much appreciated!

CodePudding user response:

I've seen other examples where people are capturing and using parameters as part of a rewritten path

Yes, this is possible. The basic principle is the same:

RewriteEngine On

RewriteCond %{QUERY_STRING} (?:^|&)u=([\w./-]{6,})(?:&|$)
RewriteRule ^$ https://%1 [QSD,R=302,L]

%1 is a backreference to the capturing group in the preceding CondPattern. ie. the value of the u URL parameter.

([\w./-]{6,}) is just a very rudimentary check to match a semi-valid URL. This can be improved.

The (?:^|&) prefix on the regex ensures we only match the u URL parameter and not any URL parameter that simply ends in u.

This only redirects requests for the root, as in your example. A malicious user could turn your site into a relay to forward traffic.

However, without further validation of the URL being redirected to this is open to abuse and should not be used.

  • Related