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

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 *

If a user does not come from, 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 on

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

map $http_referer $referrer_check { 
default 1;
"" 0;
"*" 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’s users, Android’s users and iOS’ users. Other ones will get HTTP 400 error.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store