how should i redirect http to https and also www to naked root domain?
if i am hosting a site in cloudflare worker, how should i redirect http to https and also www to naked root domain?
1 Reply
You can configure HTTP to HTTPS and www to the naked root domain by using a Cloudflare Worker with some basic redirection logic.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
// Redirect HTTP to HTTPS
if (url.protocol === 'http:') {
url.protocol = 'https:'
return Response.redirect(url.toString(), 301)
}
// Redirect www to naked domain
if (url.hostname.startsWith('www.')) {
url.hostname = url.hostname.slice(4) // Remove "www."
return Response.redirect(url.toString(), 301)
}
// If no redirects needed, continue with the request
return fetch(request)
}