Replace dashes with hyphens in URL

I searched the community but have not been able to find the answer.

How do I replace / (slashes) with - (hyphens) in a specific set of URLs?

For example, I have a specific set of URLs that are formed like:

Where name-of-organization contains hyphens, city-of-organization could contain hyphens, and zipcode is a number.

I’m trying to rewrite the URLs so that it becomes:

So basically, take the slashes / between name-of-organization, city-of-organization, and zipcode and rewrite them as -.

Is there a way to do so in Cloudflare?

htaccess is not an option in this case so I’m hopeful it’s possible to do it in Cloudflare.

Thanks for any help you can provide.


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 => {

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.

Hope this helps

This is very helpful. Thank you.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.