Question 6
Subject: Redirection Based on User Agent
I want to redirect visitors with a specific user agent (e.g., *MSIE 8.0*) to a different page. It seems this is not possible with Cloudflare Page Rules. Is there any other way to achieve that using Cloudflare?
--------------------------------------------------------------------------------------------------------------------------------------------
To achieve user agent-based redirection with Cloudflare, you can use Cloudflare Workers. Here’s how:
- Create a New Worker: Log in to your Cloudflare dashboard, go to the Workers section, and click on Create a Worker.
- Write Your Worker Script: Use the following script to check the `User-Agent` header and redirect users based on their user agent:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const userAgent = request.headers.get('User-Agent');
// Check if the User-Agent contains "MSIE 8.0"
if (userAgent && userAgent.includes('MSIE 8.0')) {
// Redirect to a different page
return Response.redirect('https://example.com/old-browser', 302);
}
// If no match, continue as normal
return fetch(request);
}
- Deploy the Worker: After writing the script, click Save and Deploy.
- Assign the Worker to Your Domain: In the Workers tab, select Triggers and add a route that matches your domain (e.g.,
*example.com/*). - Test Your Worker: Use a tool or browser extension to modify the `User-Agent` header to test the redirection.
This setup will ensure that users with the specified user agent are redirected accordingly. If you encounter any issues or need further assistance, feel free to reach out with additional details.