Url rewrite by Cloudflare workers

We want our country language url Ex: http://www.abc.com/en-in to be rewrite to http://www.in.xyz.com/en

Could you suggest how best to achieve this in cloudflare or with cloudflare workers

Hi [thomas4]

Thanks for checking

Actually we want a rewrite , so that for end users the Source url in the example given http://www.abc.com/en-in remains the same but content will be fetched from destination url

Can you suggest if this can be done by workers

Keep in mind that doing a proxy to a domain that you don’t own or don’t have the legal right to proxy, would be a very quick way to get your Cloudflare account shut down.

If it’s just the rewrite you can use the following code:

const url = new URL('http://www.abc.com/en-in')
const replaceUrl = url.pathname.split('/')
.filter(i => i === 'en-in')
.map(i => `http://www.${i.split('-')[1]}.xyz.com/${i.split('-')[0]}`)

//returns http://www.in.xyz.com/en

But if you need to proxy a domain and replace the URL structure of a link then use the following example:

class HrefHandler {
	constructor(url){
		this.url = url
	}
	element(element)
	{
		const url = new URL(this.url)
		const replaceUrl = url.pathname.split('/')
		.filter(i => i === 'en-in')
		.map(i => `http://www.${i.split('-')[1]}.xyz.com/${i.split('-')[0]}`)
		
		element.setAttribute('href', replaceUrl)
	}
}

const url = 'http://www.abc.com/en-in'
const res = await fetch(url)

return new HTMLRewriter().on("a", new HrefHandler(url)).transform(res)
2 Likes

Hi, thank you very much. This is the code I’m currently looking for, and I’ve successfully implemented it on my website