Publish security.txt using a Cloudflare Worker

What do you do if your website hosting provider does not support security,txt natively or give you the ability to upload it to the correct location? Or perhaps for security or availability reasons you would prefer it to be served separately from your website for availability in case your site is compromised or down.

Well, here is a potential solution. We are going to use Cloudflare and serve security.txt from the Edge using Cloudflare workers.

Cloudflare needs to be setup already with proxy mode enabled (orange cloud) for the domain in question.

We are going to use our test domain 365labs.uk and route all requests to *365labs.uk/.well-known/security.txt to our Cloudflare worker. Start by creating a new application:

Create the sample “Hello World” Worker. We will call ours sectxt. Deploy the sample Worker and choose Edit Code.

Paste in the following code customising it as you wish. You can use securitytxt.org to create a sample file with the correct syntax and options and paste the relevant parts into the code.

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

async function handleRequest(request) {
  // Define the content of your security.txt file
  const securityTxtContent = `Contact: [email protected]
Expires: 2025-12-31T23:59:00.000Z
Preferred-Languages: en
Canonical: https://365labs.uk/.well-known/security.txt
Preferred-Languages: en`

// Set the appropriate headers for the security.txt file
  const headers = {
    'Content-Type': 'text/plain',
    'Cache-Control': 'public, max-age=3600' // Cache the file for 1 hour (adjust as needed)
  }

  return new Response(securityTxtContent, { status: 200, headers })
}

Choose Save and Deploy

Go back to the main Workers dashboard and click View routes.

Add a new route for the URI, we are using *365labs.uk/.well-known/security.txt and select your domain for the zone:

 
Previous
Previous

Does a 🔒 mean a website is secure?

Next
Next

What is containerization and do I need it?