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.

Read More

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?

Related posts

2 comments

  1. 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/.

  2. Instead of replacing the first (.*), you should have just added to it:

    Source: /(?!friends/?)(.*)?(.*)$
    Target: /$1
    

    The negative look-ahead group (?!friends/?) doesn’t match anything by itself; it just prevents certain matches.

Comments are closed.