Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save isaumya/c2667b737d4e1e48a8ebb0df24b89a39 to your computer and use it in GitHub Desktop.
Save isaumya/c2667b737d4e1e48a8ebb0df24b89a39 to your computer and use it in GitHub Desktop.
Cloudflare Workers code to manage redirection of a domain and adding extra security headers to the correct hostname
/**
* CloudFlare Worker to handle each request
* and based on the given condition either redirect it to
* the proper URL
* OR add the security headers in case of Status 200
* @author Acnam Infotech
* @explanation https://acnam.com/why-and-how-to-use-cloudflare-workers-explained-with-sample-code/
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
// Convert the request to a mutable URL
const requestURL = new URL(request.url)
// Check if the website is using correct hostname, protocol or using a port
// which should not be redirected
if(
(
requestURL.hostname === 'www.example.com' &&
requestURL.protocol === 'https:'
) ||
(
requestURL.hostname === 'example.com' &&
requestURL.protocol === 'https:' &&
requestURL.port === '2083'
)
) {
// No need to redirect the URL. Just add the necessary Security Headers
let response = await fetch(request)
// Make the headers mutable by re-constructing the Response.
response = new Response(response.body, response)
// Add the security headers we want to add to our response
response.headers.append('X-Frame-Options', 'DENY')
response.headers.append('Content-Security-Policy', 'block-all-mixed-content')
response.headers.append('X-XSS-Protection', '1; mode=block')
// Return the response
return response
} else {
// We need to redirect the URL to the correct hostname
// Have to redirect the URL to the proper hostname and protocol
requestURL.hostname = 'www.example.com'
requestURL.protocol = 'https:'
// Make the redirect
return Response.redirect(requestURL, 301)
}
}
@zakirsajib
Copy link

Good one.

@isaumya
Copy link
Author

isaumya commented Feb 8, 2021

Thanks, @zakirsajib. Enjoy. 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment