Skip to content

Instantly share code, notes, and snippets.

@perusio
Created October 31, 2011 01:28
Show Gist options
  • Save perusio/1326701 to your computer and use it in GitHub Desktop.
Save perusio/1326701 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;
}
@marianocibelli
Copy link

marianocibelli commented Feb 23, 2017

Its a pretty old post but in case someone want to detect tablet and mobile separately here is my code

map $http_user_agent $ua_device {
	default 'desktop';
	~*(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|mobile.+firefox|netfront|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ ce|xda|xiino/i 'mobile';
	~*android|ipad|playbook|silk/i 'tablet';
}

add_header x-ua-device $ua_device;

@bsushant-athena
Copy link

How to block requests from rest clients , I tried this but still I'm not able to block Postman requests ?
map $http_user_agent $is_browser {
~*(MSIE|Firefox|Safari|Opera) 0;
~*spider|crawl|slurp|bot 1; # bots
default 1;
}

@fperana
Copy link

fperana commented Mar 28, 2019

I think you've reversed the logic, default should be 0 and in case you detect a browser (MSIE, Firefox, etc.) you want 1.

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