Seeking Help to Dynamically Rewrite URLs Based on Language Query Parameters

I am looking to create a transform rule to dynamically modify URLs based on specific language parameters in the query string. Here’s what I need:

Goal:
For any incoming request to example.com, if the URI query string specifies lang=de, lang=es, or lang=ar, I want to dynamically insert the value of lang immediately after the domain name in the URL, maintain the rest of the path as it is, and remove the lang parameter from the query string.

Example Scenario:

Original URL: example.com/about-us/?cid=73456345&lang=de
Desired Rewritten URL: example.com/de/about-us/?cid=73456345
Requirements:

  1. The hostname must be example.com.
  2. The URI query must contain lang=de, lang=es, or lang=ar.
  3. Insert the language value (de, es, ar) directly after the domain name in the URL.
  4. Retain the existing path and other query parameters.
  5. Remove the lang parameter from the query string.

Can anyone assist me in creating a transform rule that meets these requirements? Any advice or examples of similar implementations would be greatly appreciated!

Thank you in advance!

Hi @koundou

Could you please try and see if this will work?

Hello Iouise2

Yes, I tried but it doesn’t work.

@louise2, globbing (wildcard pattern matching, or in other words expanding a value referenced from another object via $n) is not supported in Cloudflare Rules using Page Rules-like syntax. To reference a dynamic value in the rule action like this, currently you need to use regex_replace function. We’re working internally on making this easier for simple use-cases.

@koundou, if you are using Business or Enterprise plan, you can achieve this by using the aforementioned regex_replace function in Transform Rules as shown in this example.

However, complex request modifications like this are usually easier to implement via Snippets. If you let me know the domain name / zone where you would like to try it out, I can enable it for you and help with testing.

2 Likes

Hello @ncano ,

I have a Cloudflare Pro Plan. Is it possible to achieve this with the existing plan?

Not through regex_replace, but you can use Snippets for free to do this once it’s enabled for your zone.

Can you enable snippets for me?

What’s the zone / domain name you would like Snippets enabled on?

Hello @ncano

Is it possible to share this private or hidden?