Skip to contentSkip to main navigation Skip to footer

How To Use Redirects with Regular Expression & Regex?

A regular expression, often referred to as regex, is a set of characters used to identify patterns within a given piece of text. In the context of Squirrly > Redirects, a plain URL match corresponds to a single URL, while a regex URL can match multiple URLs.

Beyond just matching URLs, regular expressions in Squirrly > Redirects have the capability to extract information from the source URL and transfer it to the target URL. For instance, using the regex /my-url/.* will match requests for various URLs starting with “/my-url/,” allowing flexibility in redirection.

Understanding the syntax is crucial. The .* in /my-url/.* represents a regular expression, signifying “match /my-url/ followed by any sequence of characters.” To enable regular expression matching in Squirrly > Redirects, ensure the ‘regex’ option is enabled.

Regular Expression Syntax: The .* in a regular expression like /my-url/.* is interpreted as “any character” (.), and the asterisk (*) means any number of the preceding expression. Regular expressions can become quite intricate, allowing for detailed and complex patterns.

Extracting Source Information: Regular expressions not only match multiple URLs but also extract information from the source URL for use in the target URL. For instance, using /oldpage/(.*) captures data within the brackets, allowing it to be reused in the target URL as $1.

Infinite Loops: A common challenge with regular expressions is the potential for infinite redirects. This occurs when a regex redirects to a URL caught by the same regex, creating a loop. To prevent this, using the ^ character at the start of the regex limits matches to the beginning of the URL.

Testing Regular Expressions: Various online tools, such as regexr.com and regex101.com, can help test and experiment with regular expressions. Keep in mind that Squirrly SEO uses PHP’s regular expressions (PCRE), which may differ slightly from other libraries.

Common Regular Expressions for WordPress: Below are some commonly used regular expressions for WordPress with the ‘regex’ option enabled:

  • Redirect date and name permalink:
    • Source: ^/\d{4}/\d{2}/\d{2}/(.*)
    • Target: /$1
  • Redirect date, name, and category permalink:
    • Source: ^/\d{4}/\d{2}/\d{2}/.?/(.)
    • Target: /$1
  • Redirect all URLs to /blog/ except those starting with /blog/:
    • Source: ^/(?!blog)(.*)
    • Target: /blog/$1
  • Redirect every page on the old site to the new site:
    • Source: /(.*)
    • Target: https://newsite.com/$1
  • Remove .html from Blogger pages:
    • Source: ^/(.*?).html$
    • Target: /$1/