Nginx – How to whitelist User Agent string

conditionalconfigurationnginxstringsuseragent

I'm trying to whitelist a very specific User Agent string in Nginx. The below examples demonstrate how to whitelist general types of browsers (eg mozilla or chrome), but the string I want to whitelist has / and ( which breaks the nginx conf.

How to whitelist a user agent for nginx?

https ://gist.github.com/supairish/2951524

https ://www.scalescale.com/tips/nginx/block-user-agents-nginx/

https ://www.cyberciti.biz/faq/nginx-if-conditional-http_user_agent-requests/

https ://stackoverflow.com/questions/17674293/allow-only-one-user-agent-block-the-rest-in-nginx

Is it possible to whitelist the below string?

if ($http_user_agent ~* (Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36) ) {
return 403;
}

Best Answer

The regular expression contains embedded spaces and should therefore be quoted. The parentheses and periods have special meaning in a regular expression and should be escaped using a backslash. The forward slash is fine.

"\(Mozilla/5\.0 \(Windows NT 10\.0; Win64; x64\) AppleWebKit/537\.36 \(KHTML, like Gecko\) Chrome/58\.0\.3029\.110 Safari/537\.36\)"

If this is the entire string to test, you can avoid the escaped regular expression and use = with a quoted string instead:

if ($http_user_agent = "..." ) { return 403; }

See this document for more.

By the way, if you are white listing, the test should be !~* or != to reject the mismatching strings.

Related Topic