Mobile app version of vmapp.org
Login or Join

Login to follow query

More posts by @Samaraweera270

2 Comments

Sorted by latest first Latest Oldest Best

 

@Ann8826881

Note that if you need to match against the query string, you need to compare against the QUERY_STRING server variable in a mod_rewrite RewriteCond directive. You can't match against the query string using a mod_alias Redirect (or RedirectMatch) or the RewriteRule (mod_rewrite) pattern - these all match against the URL-path only, which notably excludes the query string.

Otherwise, there is nothing special about the % in the query string, it is matched as a literal % in the QUERY_STRING server variable (which is not decoded). Try the following:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^data%5Bbranch%5D=xyz$
RewriteRule ^folder/site$ www.example2.com/test/? [R=302,L]


It is more efficient to match the URL-path in the RewriteRule pattern, rather than using a condition to match against REQUEST_URI. The RewriteRule pattern is first matched, and only if this is successful are the conditions (above it) processed.

No need to wrap the query string value in double quotes. But if you want to match just that query string, you will need start/end anchors (ie. ^...$). (Or use the exact match - lexicographically equal - operator prefix, =, ie. =data%5Bbranch%5D=xyz. Everything after the = prefix is treated as a literal string, not a regex).

The ? is required on the end of the RewriteRule substitution in order to remove the query string from the request, otherwise it will be passed through to the substituted URL. By ending the URL with ? essentially creates an empty query string (the ? itself is not included in the resulting URL). (If you are on Apache 2.4+ then you can use the QSD - Query String Discard - flag instead.)

The L flag ensures no other rules are processed if this is successful. Which is usually what you want to do in the case of an external redirect.

If this is to be a permanent redirect then change the R=302 (temporary) flag to R=301 once it is working OK. If you don't explicitly use the R flag to force an external redirect, it will be implicitly redirected because you have specified an absolute URL in the substitution. It is always better to be explicit. (NB: 301/permanent redirects are cached by the browser so it is often easier/safer to test with 302/temp redirects first. Or test with browser caching disabled.)

10% popularity Vote Up Vote Down


 

@Murray155

Seems like I found an answer to my own question. Guess it is the right way to do it, but anyway:

RewriteCond %{REQUEST_URI} ^/folder/site$
RewriteCond %{QUERY_STRING} "data%5Bbranch%5D=xyz"
RewriteRule (.*) www.example2.com/test/

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme