Hosting a Cloudflare Worker at a specific Subdirectory or URL path is pretty straight forward and it will only take a few minutes to setup.
In this tutorial I will create a Cloudflare Worker that returns a simple ‘Hello World’ response that will be available at https://www.brendansluke.com/helloworld
Create a Cloudflare Worker
If you haven’t already created the Cloudflare Worker that you want to host at a specific URL path. Go ahead and create the Cloudflare Worker via the Cloudflare Dashboard by navigating to the ‘Workers’ section and clicking the ‘Create a Worker’ button.
Build the Functionality of your Cloudflare Worker
If the functionality of your Cloudflare Worker is not already created, you should do that now.
I’ve created a simple Worker that returns ‘Hello World’ when it is called:
Setting up the Route for the Cloudflare Worker
The next step is to setup a custom route in the Workers section of your domain.
Navigate to the domain that you want the Worker to be hosted at, then navigate to the Workers section.
Here, we will click ‘Add route’ to add a specific URL path for your Worker.
You will now be prompted to define a route and to select your Worker from the dropdown.
Fill in the route with your specific URL path or subdirectory and select a Worker from the dropdown, then click ‘Save’.
Here is what your ‘Add route’ data should look like:
After you click ‘Save’, you should see a little notice saying that the Worker was assigned to a specific route:
Testing Out the Cloudflare Worker at your Specific URL
At this point our Worker should be behind our specific subdirectory (/helloworld), let’s test it out!
It’s very simple to test, just open a new browser tab and paste in the URL that you specified when setting up the route for the Worker.
If everything is working correctly, you should see the response from your Cloudflare Worker:
Tips for Troubleshooting Your Cloudflare Worker
If your specific URL path does not return the correct response from your Cloudflare Worker, try the following:
- Make sure that you have either an A record or a CNAME record for the specific domain/subdomain that you referenced while adding your route.
- Check that your Worker is actually responding properly (regardless of your domain specific path) by navigating to the ‘development’ link that Cloudflare provides in the editing section for your specific Cloudflare Worker.