How to disallow some referrers and allow some user agents on Nginx?

adil
2 min readMay 26, 2018

The scenario: A server has to serve some static files, which have HTTP Referrers. However, the mobile devices don’t send any HTTP Referrers.

Let’s say, your images must be served for the users who come from *.google.com

If a user does not come from google.com, then the user would see HTTP 400.

However, if a user comes from the mobile application, then the user won’t see the files. Because the mobile application won’t send any HTTP Referrer. You may want to serve some static files for the mobile application’s users as well.

Photo by Francisco Galarza on Unsplash

We are going to allow only Google.com’s users and Android/iOS users. So, only Google.com’s users and the mobile application’s users will be allowed.

map $http_referer $referrer_check { 
default 1;
"~google.com" 0;
"*.google.com" 0;
}

map $http_user_agent $mobile_check {
default 1;
~(Android|Darwin) 0;
}

We define the HTTP Referrer sources and the mobile applications in the Nginx configuration file.

You probably know, Nginx doesn’t have AND/OR operators. In some cases, you can use RegEx instead of OR operator, though. It is not theme of this post.

set $flag "0";if ($referrer_check) {
set $flag "1";
}
if ($mobile_check) {
set $blockit $flag;
}
if ($blockit) {
return 400;
}

We accept only Google.com’s users, Android’s users and iOS’ users. Other ones will get HTTP 400 error.

--

--