Back to Home

Question 6: Redirection based on user agent

Customer Inquiry

Subject: Redirection based on user agent

I want to redirect visitor with specific user agent (*MSIE 8.0* for example) to a different page. It seems this is not possible with Cloudflare Page Rules.
Is there any other way to achieve that using Cloudflare?


Response to Customer

Hello,

You are correct, redirecting based on the User-Agent header is not possible with Page Rules. However, this is a perfect use case for Cloudflare Workers!

Cloudflare Workers is a powerful serverless platform that allows you to run JavaScript code at the edge of our network.
You can use a simple Worker script to inspect the User-Agent header of an incoming request and issue a redirect if it matches a specific pattern.

Here is an example script that would redirect any visitor with "MSIE 8.0" in their User-Agent to a different page:

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

async function handleRequest(request) {
  const userAgent = request.headers.get('User-Agent') || ''
  if (userAgent.includes('MSIE 8.0')) {
    return Response.redirect('http://example.com/unsupported-browser.html', 301)
  }
  return fetch(request)
}
    

You can add this script to a new Worker in the Cloudflare dashboard and then assign it to a route (e.g., *example.com/*) to have it run on all requests to your site.

Let me know if you have any questions about setting this up.

Best regards,

João Estêvão
Customer Support Engineer
Cloudflare


Thought Process

  1. Confirm the Limitation:
    First, I need to confirm that the customer is correct about the limitation of Page Rules.
    This builds trust and shows that I've understood their question.

  2. Introduce the Solution:
    This is a great opportunity to introduce Cloudflare Workers as the solution.
    I should briefly explain what Workers are and why they are the right tool for this job.

  3. Provide a Code Snippet:
    Providing a working code snippet is extremely helpful.
    It gives the customer a concrete example they can copy, paste, and adapt. The code should be simple and well-commented.

  4. Explain the Next Steps:
    I should briefly explain what to do with the code (add it to a Worker, assign a route) to guide them through the process.


Tools I Would Use

Cloudflare Workers Dashboard:
The primary tool would be the Workers editor in the Cloudflare dashboard.
I would use it to write and test the example code before sending it to the customer. The built-in debugger is perfect for this.

cURL:
I would use `curl` to test the worker once it's deployed.
A command like `curl -I -A "MSIE 8.0" http://example.com/` would allow me to spoof the User-Agent and verify that the redirect is working correctly.
I would expect to see a `301 Moved Permanently` response with the new location.