How to redirect a domain to a path?

There are many reasons to redirect a domain or a subdomain to a path. The reason why we use this technique at Kooyal is to get more SEO juice for our primary domain of kooyal.com. If we didn’t use this technique our Blog would be at something like wordpress.kooyal.com
instead of kooyal.com/blog and Documentation would be at docs.kooyal.com
instead of kooyal.com/docs.
Table of Contents
Redirect a Domain – Setup with Cloudflare Worker
We use Cloudflare to host our DNS. And luckily it is very easy to set this up on Cloudflare using their Worker service and free for limited usage.
1. Create a new Worker
Go to Workers tab in Cloudflare dashboard and Create a Service.

Next, enter a service name and select Create Service. It doesn’t matter which starter code you use because we will be replacing it in the next step.
2. Setup a path to redirect a domain
Now, let’s setup a path you want this worker to run on. Go to Triggers tab, and add the path you desire.

3. Setup worker script
Next, go back to Resources and click on Quick Edit under Worker. And enter the script below.
async function handleRequest(request) {
const url = new URL(request.url)
const targetPath = url.pathname
return await fetch(`https://tools.kooyal.com${targetPath}`)
}
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request))
})
The above script is very simple. It takes all request coming to kooyal.com/tools* and redirects them to another subdomain, tools.kooyal.com in this case.
Here’s another example that would be very useful for anyone trying to do the same behavior for a WordPress blog.
const config = {
subdomain: "blog.kooyal.com",
root: "kooyal.com",
blogPath: "blog",
}
async function handleRequest(request) {
const url = new URL(request.url)
let targetPath = url.pathname
let response = await fetch(`https://${config.subdomain}${targetPath}`)
if (
targetPath.includes('/wp-content/') ||
targetPath.includes('/wp-includes/')
) {
return response
}
body = body.split(config.subdomain).join(config.root)
response = new Response(body, response)
return response
}
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request))
})
The above example is a bit more complex, but the idea is the same. It will respond to return all requests to /wp-content/
and /wp-includes/
without modifications since those are static content. However, it will rewrite links in all other pages from blog.kooyal.com
to kooyal.com/blog
.
You can study more complex scripts at Cloudflare Docs.
Add Robots.txt
One last thing. Don’t forget to add robots.txt to make sure search crawlers don’t index your subdomain (e.g. blog.kooyal.com). The below snippet will make sure search engines don’t crawl any content on the entire domain.
User-agent: *
Disallow: /
That’s it, you are ready to get more SEO juice to your root domain.