Is there an elegant way to block a bunch of referrers at once?

bdesham asked:

In order to prevent referrer spam, my nginx.conf contains a section like this:

if ($http_referer ~* spamdomain1.com) {
    return 444;
}
if ($http_referer ~* spamdomain2.com) {
    return 444;
}
if ($http_referer ~* spamdomain3.com) {
    return 444;
}

These rules tell nginx just to close the connection if the user has one of these referrers set. Is there a more elegant way to do this? Can I define a list of these domains and then say something like, “If the referrer is in this list then return 444”?

My answer:


I would try a map:

map $http_referer $bad_referer {
    default                  0;
    "~spamdomain1.com"       1;
    "~spamdomain2.com"       1;
    "~spamdomain3.com"       1;
}

Then use it like so:

if ($bad_referer) {
    return 444;
}

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.