I'm trying to block/allow access to a particular vhost based on string matching of the HTTP user agent name.

The version number of the application in the HTTP user agent changes, e.g.

My%20App/1.55.01 CFNetwork/711.5.6 Darwin/14.0.0
My%20App/1.49.03 CFNetwork/711.5.6 Darwin/14.0.0
My%20App/1.35.02 CFNetwork/711.5.6 Darwin/14.0.0

I want to match everything starting with My%20App/ - anything that matches should be allowed access, anything else should get HTTP 403.

I don't want to have to update the nginx config every time a new version of the app comes along.

The following works fine:

if ($http_user_agent !~* "My%20App/1.55.01 CFNetwork/711.5.6 Darwin/14.0.0") {
    return 403;

I figure I need a solution that involves hat (^) for "starts with" but I can't get nginx to accept anything I've tried.

Thanks in advance.

  • What's wrong with simple if ($http_user_agent !~ "^My App/") { return 403; }
    – Alexey Ten
    Sep 7 '15 at 7:31

Turns out that the following works.

if ($http_user_agent !~* "My%20App/*") {
    return 403;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.