Currently, I’m using Redirection plugin in WordPress to redirect all URLs that contain q question mark in this way:
Source: /(.*)?(.*)$
Target: /$1
This works well. It will redirect any link with a ?
, such as /good-friends-are-great.html?param=x
to /good-friends-are-great.html
.
However, now I need to make an exception. I need to allow /friends
to pass GET parameters, e.g. /friends?guest=1&event=chill_out&submit=2
OR /friends/?more_params
, without the parameters being truncated.
I have tried modifying the regular expression in the plugin to:
Source: /(?!friends/?)?(.*)$
Target: /$1
But this didn’t work. With the above expression, any link with ?
is no longer redirected.
Can you help?
You can use the regular expressions below:
See demo
The regex is using 2 negative look-behinds because in this regex flavor, we cannot use variable-width look-behinds.
(.*(?<!friends)(?<!friends/))
matches any number of any characters up to?
, but checks if the?
is not preceded with eitherfriends
orfriends/
.EDIT:
Here is my first regex that did not work well for the current scenario:
Its subpattern
(?:(?!friends/?).)+
matches a string that does not containfriends
orfriends/
.Instead of replacing the first
(.*)
, you should have just added to it:The negative look-ahead group
(?!friends/?)
doesn’t match anything by itself; it just prevents certain matches.