Since many websites prioritize a clean, non-www domain for user experience and SEO (Search Engine Optimization), redirects from www subdomains are commonplace. Previously, Cloudflare's Page Rules offered a straightforward solution. However, with Page Rules being deprecated, here's how to achieve www redirects using Cloudflare's alternative methods.
Using "Redirect Rules"
- Log in to Cloudflare and select the desired domain.
- Navigate to the "Rules" tab.
- Click "Create Redirect Rule".
- In the "If the URL matches" field, enter
*www.example.com/*
(replaceexample.com
with your domain). - In the "Then the settings are" field, select "301 - Permanent Redirect" and enter
https://example.com/$1
(replaceexample.com
with your domain). - Click "Save and Deploy".
Using "Workers"
- Log in to Cloudflare and select the desired domain.
- Navigate to the "Workers" tab.
- Click "Create a Worker".
- In the editor, replace the existing code with the following:
addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url) if (url.hostname.startsWith('www.')) { url.hostname = url.hostname.replace('www.', '') return Response.redirect(url, 301) } return fetch(request) }
- Click "Save and Deploy".
By following these steps, you can effectively redirect www subdomains to non-www domains using Cloudflare's "Redirect Rules" or "Workers." This ensures a seamless transition for users and maintains SEO benefits associated with a clean domain structure.