Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match URL that does not begin with string in WP Redirection plugin

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?

like image 292
GooDoo Avatar asked Dec 22 '25 08:12

GooDoo


1 Answers

You can use the regular expressions below:

/(.*(?<!friends)(?<!friends/))\?.*$

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 either friends or friends/.

EDIT:

Here is my first regex that did not work well for the current scenario:

/((?:(?!friends/?).)+)\?.*$

Its subpattern (?:(?!friends/?).)+ matches a string that does not contain friends or friends/.

like image 99
Wiktor Stribiżew Avatar answered Dec 23 '25 21:12

Wiktor Stribiżew