Skip to content

Instantly share code, notes, and snippets.

@tux255
Forked from perusio/gist:1326701
Created May 7, 2018 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tux255/afe9331cf64b06adfcaa3a4fc67805d9 to your computer and use it in GitHub Desktop.
Save tux255/afe9331cf64b06adfcaa3a4fc67805d9 to your computer and use it in GitHub Desktop.
Mobile device detection in Nginx with just 7 lines of configuration
### Testing if the client is a mobile or a desktop.
### The selection is based on the usual UA strings for desktop browsers.
## Testing a user agent using a method that reverts the logic of the
## UA detection. Inspired by notnotmobile.appspot.com.
map $http_user_agent $is_desktop {
default 0;
~*linux.*android|windows\s+(?:ce|phone) 0; # exceptions to the rule
~*spider|crawl|slurp|bot 1; # bots
~*windows|linux|os\s+x\s*[\d\._]+|solaris|bsd 1; # OSes
}
## Revert the logic.
map $is_desktop $is_mobile {
1 0;
0 1;
}
@tux255
Copy link
Author

tux255 commented May 7, 2018

Usage example:
set $mobile_rewrite do_not_perform;

if ($is_mobile) {
set $mobile_rewrite perform;
}

if ($mobile_rewrite = perform) {
rewrite ^ http://m.domain.com$request_uri? redirect;
break;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment