Question
Can I redirect based on the User-Agent string with Cloudflare Workers?
Asked by: USER5338
70 Viewed
70 Answers
Answer (70)
Yes, you can redirect based on the User-Agent string. The `User-Agent` is available in the `request.headers`. You would typically parse this header to detect specific browsers or devices and then issue a redirect.
```javascript
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const userAgent = request.headers.get('User-Agent');
const url = new URL(request.url);
if (userAgent && userAgent.includes('Mobile') && url.pathname === '/desktop-page') {
return new Response(null, {
status: 302,
headers: {
'Location': '/mobile-page'
}
});
}
return fetch(request);
}
```