Search code examples
nginxhotlinking

Nginx hotlink protection for image with ID - am I doing it wrong?


I'm having a little bit of trouble working out a nginx hotlink protection code for images that carry a ID value on the end as well as using the . after the image. I'm only looking to block other 3 websites from leeching our images.

eg;

mydomain.com/attachments/someimage-jpg.179394/
mydomain.com/attachments/6-jpg.185288/

The way images display it always carries the -jpg or -gif followed by .{ID} and trailing slash.

eg;

/attachments/image-jpg.12345/

I was trying regular expressions (I'm obviously hopeless at this so far) but they have no effect, but don't cause any errors on nginx reload either.

location /attachments/([0-9a-zA-Z])-(png|jpg|jpeg|gif).([0-9]+)/ {
if ($http_referer ~ ^(www.example.com|www.example.org|www.example.net)) {
  rewrite ^ url/to/leech.jpg;
 }
}

Sorry if my above example is everything that can be done wrong, done wrong, but I'm a pcre(?) newbie. Am I even close?


Solution

  • Your regular expression is wrong

    replace

    /attachments/([0-9a-zA-Z])-(png|jpg|jpeg|gif).([0-9]+)
    

    by

    /attachments/([0-9a-zA-Z])+-(png|jpg|jpeg|gif)[.]([0-9]+)
    

    because ([0-9a-zA-Z]) just match 1 character and . need be escaped