Search code examples
apachemod-rewrite

Apache mod_rewrite rule issue that causes an infinite loop


We must redirect from this URL:

https://www.ourdomain.com/event/just-an-event-600922?test=620c3c875ceb1ae584920c04d02bc083

to the same without the query string:

https://www.ourdomain.com/event/just-an-event-600922

We've tried with this combination of RewriteCond and RewriteRule:

RewriteCond %{QUERY_STRING} ^test=([A-Za-z0-9]+)$
RewriteRule ^event/just-an-event-600922$ https://www.ourdomain.com/event/just-an-event-600922 [L,R=301]

But it apparently causes an infinite loop. Any idea how to fix this?


Solution

  • You were close, but you're missing the ? at the end. Actually, the query string is appended automatically when it comes to the redirection, resulting in a loop. By using ?, you kind of reset the query string.

    So, your solution:

    RewriteCond %{QUERY_STRING} ^test=[A-Za-z0-9]+$
    RewriteRule ^(event/just-an-event-600922)$ /$1? [L,R=301]
    

    Note 1: you don't need to match and remember the test value by using parenthesis, since you don't use it.

    Note 2: you can match the RewriteRule so that you don't need to write it one more time for the redirection target (notice the ? at the end, which is really the point to your initial question here).