Regular Expressions 101

Community Patterns

Apache: if a url comes with & but without a ? starting the query param, replace the first & with a ?

0

Regular Expression
PCRE (PHP <7.3)

/
^(?!.*\?)(.*?)\&(.*?)$
/
gm

Description

If you got a malformed URL with a query string not starting with a question mark, this Apache rule will catch it and make a redirection, replacing the first ampersand with the mandatory question mark for a query string.

The negative lookahead will make sure that it don't replaces a well formed query string (if the tested text contains a question mark)

RewriteRule ^(?!.*\?)(.*?)\&(.*)$ /$1?$2 [R=302,NC,L]
Submitted by anonymous - 5 years ago