Hi
I believe you can achieve URL rewriting or modification In Cloudflareusing Cloudflare Workers. Workers allow you to run JavaScript code on Cloudflare’s edge servers, enabling you to manipulate requests and responses.
For your specific case, you want to replace slashes with hyphens in a set of URLs. Here’s a simple Cloudflare Worker script that accomplishes this:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Get the requested URL
let url = new URL(request.url)
// Check if the URL matches the pattern you want to rewrite
if (url.pathname.startsWith('/menu/')) {
// Extract the parts between slashes
let parts = url.pathname.split('/').slice(2)
// Join the parts with hyphens
let newUrlPath = '/menu/' + parts.join('-')
// Create a new URL with the modified path
let newUrl = new URL(url)
newUrl.pathname = newUrlPath
// Redirect to the new URL
return Response.redirect(newUrl, 301)
}
// If the URL doesn't match, pass the request through unchanged
return fetch(request)
}
This script checks if the requested URL starts with “/menu/” and then replaces slashes with hyphens in the subsequent parts of the path. It issues a 301 (permanent) redirect to the modified URL.