The following examples will redirect visitors using mobile devices — based on the request user agent string — to a different hostname.
This example static redirect will redirect requests for the current zone (example.com) from mobile users to m.example.com without preserving the URI path in the original HTTP request.
When incoming requests match
- Enter the following expression in the Expression Editor:
not http.host in {"m.example.com"} and (http.user_agent contains "mobi" or http.user_agent contains "Mobi")
Then
- Type: Static
- URL:
https://m.example.com/ - Status code: 302
Notes about this example:
- The
not http.host in {"m.example.com"}condition prevents redirect loops. - The user agent condition follows Mozilla's recommendation ↗︎ for identifying mobile devices.
- The Then > URL value should use the same hostname you entered in the
http.hostcondition of the rule's filter expression. - Include the URI scheme (
https://) in the target URL. Cloudflare sends a target URL without a scheme, such asm.example.com, unchanged in theLocationheader, and browsers treat it as a relative path on the current hostname. - This example uses a
302(temporary) status code. Browsers can cache301(permanent) redirects, and Cloudflare does not add aCache-Controlheader to redirect responses. A visitor who later uses the same browser on a desktop device might keep receiving a cached301redirect. - You can redirect users to other zones on Cloudflare or to other hostnames not on Cloudflare.
This example single redirect will redirect requests for the current zone (example.com) from mobile users to m.example.com, keeping the URI path of the original HTTP request.
When incoming requests match
- Enter the following expression in the Expression Editor:
not http.host in {"m.example.com"} and (http.user_agent contains "mobi" or http.user_agent contains "Mobi")
Then
- Type: Dynamic
- Expression:
concat("https://m.example.com", http.request.uri.path) - Status code: 302
Notes about this example:
- The
not http.host in {"m.example.com"}condition prevents redirect loops. - The user agent condition follows Mozilla's recommendation ↗︎ for identifying mobile devices.
- The hostname in Then > Expression should be the same as the one you entered in the
http.hostcondition of the rule's filter expression. - Depending on your use case, you might want to enable Then > Preserve query string to also keep the query string of the original request.
- You can redirect users to other zones on Cloudflare or to other hostnames not on Cloudflare.