Traditionally mobile devices have been detected by comparing the HTTP User-Agent header against a list of well known mobile UA strings. A novel approach instead tries to detect the presence of a desktop OS - anything which is found to not be a desktop OS must then be mobile.
This results in far less false positives.
I've written a post with sample code in Python here:
http://notnotmobile.appspot.com
Here is a snippet:
import re
# Some mobile browsers which look like desktop browsers.
RE_MOBILE = {
"iphone" : re.compile("ip(hone|od)", re.I),
"winmo" : re.compile("windows\s+ce", re.I)}
RE_DESKTOP = {
"linux" : re.compile(r"linux", re.I),
"windows" : re.compile(r"windows", re.I),
"mac" : re.compile(r"os\s+(X|9)", re.I),
"solaris" : re.compile(r"solaris", re.I),
"bsd" : re.compile(r"bsd", re.I)}
# Bots that don't contain desktop OSs.
RE_BOT = re.compile(r"(spider|crawl|slurp|bot)")
def is_desktop(user_agent):
# Anything that looks like a phone isn't a desktop.
for regex in RE_PHONE.values():
if regex.search(user_agent) is not None:
return False
# Anything that looks like a desktop probably is.
for regex in RE_DESKTOP.values():
if regex.search(user_agent) is not None:
return True
# Bots get the desktop view.
if RE_BOT.search(user_agent) is not None:
return True
# Anything else is probably a phone!
return False
def get_user_agent(request):
# Some browsers put the User-Agent in a HTTP-X header
if 'HTTP_X_OPERAMINI_PHONE_UA' in request.headers:
return request.headers['HTTP_X_OPERAMINI_PHONE_UA']
elif:
# Skyfire / Bolt / other mobile browsers
...
else:
return request.headers.get('HTTP_USER_AGENT', '')
def view(request):
user_agent = get_user_agent(request)
if is_desktop(user_agent):
return desktop_response()
else:
return mobile_response()