views:

75

answers:

2

Hey,

I'm using NGINX to segment mobile traffic between a mobile WAP/HTML site. Looks like the best way to do this is going to be to check the UA's preference for content by checking the HTTP Accept Header.

A preference for WAP is indicated by the appearance of a 'wap' mimetype in the header before an 'html' or wildcard mimetype.

So a Sony Ericsson w300i has a preference for WAP:

multipart/mixed, application/vnd.wap.multpart.mixed,applicatnoin/vnd.wap.xhtml_xml,application/xhtml+xml,text/ved.wap.wl,*/*,text/x-hdml,image/mng,/\image/x-mng,ivdeo/mng,video/x-mng,ima/gebmp,text/html

And a Blackberry Bold has a preference for HTML:

text/html,application/xhtml+xml,application/vnd.wap.xhtml+xml,application/vnd.wp.wmlc;q=0.9,application/vnd.awp.wmlscriptc;q=0.7,text/vnd.wap.wml;q=07,/vnd/.sun.j2me.app-descriptor,*/*;q=0.5

Since I'm in NGINX land, it seems like the best tool I have is NGINX's regular expressions (PCRE).

Right now I'm trying to use a negative lookahead to assert "The accept header contains WAP but not preceeded by HTML":

(?!html.*)wap

But this isn't correct. Is there a different way I can think about this problem? Or my matching logic?

So far I've found these regex resources useful:

http://www.regular-expressions.info/completelines.html http://www.zytrax.com/tech/web/regex.htm http://wiki.nginx.org/NginxHttpRewriteModule

Thanks!


Thanks for the answer, here are the related tests:

import re

prefers_wap_re = re.compile(r'^(?!(?:(?!wap).)*html).*?wap', re.I)

tests = [
    ('', False),
    ('wap', True),
    ('wap html', True),
    ('html wap', False),
]

for test, expected in tests:
    result = prefers_wap_re.search(test)
    assert bool(result) is expected, \
        'Tested "%s", expected %s, got %s.' % (test, expected, result)
+1  A: 

The simplest way to do this is with a lookbehind instead of a lookahead. Since that is not supported you can try to emulate a lookbehind with a lookahead:

^(?!(?:(?!wap).)*html).*?wap

Not pleasant to read, but it should work.

Rubular

Mark Byers
I wish :) NGINX uses pcre which doesn't support variable length lookbehind assertions: [emerg]: pcre_compile() failed: lookbehind assertion is not fixed length in "(?<!html.*)wap" at ")wap" in /etc/nginx/nginx.conf:46
jbox
@jbox: I've updated my answer. Does that work for you?
Mark Byers
Tentatively, yes it does :)
jbox
This works perfect, thanks so much!
jbox
A: 

For negative look behind, and a "micron" more performance, perhaps negative look behind with non-greedy matching:

(?<!html.*?)wap
Brent Arias