Detect and handle User-Agent with WordPress and CloudFront

CloudFront is great out of the box, but there is a feature common to WordPress that it does not natively support.

That feature is wp_is_mobile(), and it's great for creating custom conditionals or content that only display or does not display on mobile.

The catch is that CloudFront does not send User-Agent header info to the origin server. However, you can employ the following solutions to identify mobile browsers' User Agent with CloudFront.

  1. Install and activate Nginx Mobile Theme
  2. Use wp_is_mobile() alt functions


Install and activate Nginx Mobile Theme

This plugin allows you to switch theme according to the User-Agent on the NGINX reverse proxy and enable you to handle header data sent from CloudFront. To enable this feature, install and activate the plugin.

For more details, please check Configuration on Nginx Mobile Theme.

Use wp_is_mobile() alternative

Add the following code to functions.php in the theme directory to create the wp_is_mobile() alternative function.

CloudFront sends  CloudFront-Is-Mobile-Viewer header data to the origin server if a smartphone has accessed it. These codes can detect it and handle it.

function cf_is_mobile() {
  $is_mobile = function_exists('wp_is_mobile') && WordPress_is_mobile();

    // returns true if the CloudFront assumes the browser is  smartphone
        $is_mobile = true;

    // returns true if the CloudFront assumes the browser is a tablet.
    // remove the following three lines to assume table as PC.
        $is_mobile = true;

    return $is_mobile;

Further Reading

For more info on wp_is_mobile(), check out the WordPress Codex.