Regular expression to prevent hotlinking from specific sites

200 views Asked by At

I know how to implement something like the following in my Nginx configuration to prevent hotlinking. However, I don't mind hotlinking from most sources. Even though my website has nothing to do with porn, I have weird porn sites hotlink to my images. Would there be a way to modify the following config with a regular expression to filter any hotlinking from websites that contain things like porn or xxx in the address? Thanks for the help.

location ~ .(gif|png|jpeg|jpg|svg)$ {
     valid_referers none blocked ~.google. ~.bing. ~.pinterest. ~.yahoo. mywebsite.com *.mywebsite.com;
     if ($invalid_referer) {
        return   403;
    }
}
1

There are 1 answers

2
Ivan Shatsky On

Looks like you didn't check my regex, at least using some kind of online regex tester (example), as well as you didn't care to find out what is negative lookahead in regex world means. This is exactly what you were asking for, a regex that will match anything that doesn't contain a negative lookahead pattern. Try this and check how it will work:

location ~ .(gif|png|jpeg|jpg|svg)$ {
    valid_referers ~^(?!.*(xxx|porn));
    if ($invalid_referer) {
        return   403;
    }
}

However this will block direct access to your images, and if this isn't desired, change that block to the following one (assuming your server names are not defined via a regular expression):

location ~ .(gif|png|jpeg|jpg|svg)$ {
    valid_referers none server_names ~^(?!.*(xxx|porn));
    if ($invalid_referer) {
        return   403;
    }
}