Redirect regex misbehaving when placeholder empty

  • The problem with your RegEx patterns:

    /code-examples/(.*)
    /code-examples/android/(.*)
    

    is that they only match when the ending slash (/) is present in the URL; e.g.:

    # Example 1: $1 is 'page1'
    /code-examples/page1
    /code-examples/android/page1
    
    # Example 2: $1 is '' (empty)
    /code-examples/
    /code-examples/android/
    
    # Example 3
    # No matches because the ending / is not present.
    /code-examples
    /code-examples/android
    

    where the “placeholder” (i.e. (.*)) matches the page1 in the first example, and '' (i.e. empty string) in the second example.

  • To make these work:

    /code-examples
    /code-examples/android
    

    you can use (?:/?(.*)|\b) instead of /(.*), like so:

    /code-examples(?:/?(.*)|\b)
    /code-examples/android(?:/?(.*)|\b)
    
  • But since you redirect to the same URL (/tutorials/android/$1/), you can combine those RegEx patterns like so:

    /code-examples(?:/android|)(?:/?(.*)|\b)
    

    where /code-examples(?:/android|) matches either /code-examples or /code-examples/android.

I added the redirects with the Redirection plugin.

I suppose you have something like this on the Tools → Redirection → Redirects page (in wp-admin):

Now with the combined RegEx pattern, delete the second Redirect and edit the first one like so:

Note: For the Type and Group settings, just use your existing setup.

Resources: