Brad Farleigh

Freelance wordpress websites
Perth, Australia

Freelance Wordpress Developer - Perth

Serving a subdomain from subdirectory using Cloudflare workers


Google considers subdomains seperate websites – therefore it is critical that all important information is served from the primary domain, so all of the google juice goes to the right places.

This became a problem when I recently built a new ‘strap finder’ system for my eCommerce site (watchstraps.com.au) – which I hope will serve as a backlink magnet and bring me some long-tail SEO for people looking for the watch strap sizes for their specific watch models.

The site runs on Neto (aka Maropost) which is great as a eCommerce CMS (don’t get me wrong!) – however wanted to build a complex faceted tree filter thousands of iterations, and really needed to nail the technical SEO components – and Neto just wasn’t going to cut it.

In the end I ended up using C# to build a MVP and hosted it on Azure – it’s blazing fast, and has set a really good framework for me to build out the proper product.

Main website (NETO): www.watchstraps.com.au
Strapfinder (Azure): strapfinder.watchstraps.com.au <- EWWW A SUBDOMAIN

Strapfinder – it’s rough, but it works!

Now to the problem – if the whole point of strapfinder is to get me SEO – running it from a subdomain is going to be useless, cloudflare workers to the rescue!

Using cloudflare workers to serve a subdomain from a subdirectory

I jumped in to Cloudflare, and initialised a worker with the following code – which catches the subdomain (and asset path names), and routes them to the /strapfinder subdirectory.

const mySubdomain = {
    hostname: "strapfinder.watchstraps.com.au",
    targetSubdirectory: "/strapfinder",
    assetsPathnames: ["/strapfinder-lib/", "/strapfinder-css/", "/strapfinder-js/"]
}

async function handleRequest(request)
{
    const parsedUrl = new URL(request.url)

    // if its html, get it
    if (parsedUrl.pathname.startsWith(mySubdomain.targetSubdirectory))
    {

        return fetch(`https://${mySubdomain.hostname}/${parsedUrl.pathname}`)
    }
    return fetch(request)
}

addEventListener("fetch", event =>
{
    event.respondWith(handleRequest(event.request))
})

Now, when someone goes to https://www.watchstraps.com.au/strapfinder , it actually loads a page from strapfinder.watchstraps.com.au ❤️‍🔥💯👍

Other use-cases

This could also be helpful if you have a shopify store, and want to run a blog on wordpress – you could serve blog.site.com/* from www.site.com/blog/*