Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeyBurzynski/f40ce9096caedb926f32f67323e8da51 to your computer and use it in GitHub Desktop.
Save JoeyBurzynski/f40ce9096caedb926f32f67323e8da51 to your computer and use it in GitHub Desktop.
Cloudflare Dynamic Redirect Rule: Dynamically Match and Replace URL Path Segments via RegExp [301]

Dynamically Match and Replace URL Path Segments via RegExp [301]

  • Rule Name: Dynamic Redirect of Brand Locations [301]

Expression

(http.request.uri.path matches "^/locations/.*-tires-.*.asp$")

Then.. URL Redirect

  • Type: Dynamic
  • Expression: concat("https://", http.host, lower(regex_replace(http.request.uri.path, "^/locations/.*.-tires-(.*).asp$", "/locations/${1}/")))
  • Status Code: 301
  • Preserve Query String?: false

Overview

This expression uses a Regular Expression to match incoming request URLs that follow a specific pattern.

Match Expression

The pattern ^/locations/.*-tires-.*.asp$ breaks down as follows:

  • ^ asserts the start of the line.
  • /locations/ matches URLs that begin with /locations/.
  • .* is a wildcard that matches any character (except newline) 0 or more times, used here to signify any string before -tires-.
  • -tires- specifically matches this sequence of characters, indicating a particular segment in the URL path.
  • .* again, matches any sequence of characters after -tires- and before .asp.
  • .asp matches URLs that end with .asp.
  • $ asserts the end of the line.

URL Redirect Expression

  • concat() function is used to join several string segments into one URL.
  • https:// specifies the protocol of the redirect URL.
  • http.host includes the original host name of the incoming request.
  • lower() function converts the entire resulting URL to lowercase.
  • regex_replace() function takes the original path, matches it against ^/locations/.*-tires-(.*).asp$, and replaces it with /locations/${1}/ where ${1} represents the captured group in the original RegExp (the part of the URL that comes after -tires- and before .asp).
  • This effectively changes the URL structure from /locations/<something>-tires-<brandName>.asp to /locations/<brandName>/, making the URL cleaner and more SEO-friendly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment