I recently added Google ads (Adsense) to this blog to help generate some passive income. I am hosting by blog on WordPress in a container and had to ad the “ads.txt” file and its contents to my site’s root folder. I did not feel like making changes to my container so I decided to use cloudflare workers to send back the ads.txt response.

How to send back a response using Cloudflare Workers

Your site must already be on Cloudflare. Once your site is on Cloudflare just log into Cloudflare and click on “Workers” on the left hand side. Next click on the blue “Create Service” button.

cloudflare workers

Give your Cloudflare Worker a nice name and choose the HTTP Handler template and click on “Create Service”

create a new worker service

Next, you must add a route for https://Your_Site.com/ads.txt. So click on Routes and then on the “Add Route” button.

add a route
add a route 2

You must enter your site and select the Zone (the domain name) this route is applicable to and click on “Add Route”

Keep in mind only 1 worker can respond this route. If you try and add this exact route to another worker it will not work.

add a route 3

Next, click on “Quick Edit” in the top right corner and add the below code. Then click on “Save and Deploy” at the bottom of the page. (Make sure you substitute the below response with your ads.txt data you received from Google Adsense)

save and deploy

export default {
  async fetch(request, env) {
    return new Response("google.com, pub-xxx, DIRECT, xxx", { status: 200, statusText: "OK" })
  }
}

Give it a few minutes to propogate and when you visit https://your_site.com/ads.txt this Cloudflare Worker will respond to all request.

Your can do the same for robots.txt or any other URL. This is also a great way to reduce traffic to your site especially if you are resource constrained.