12

Is there a way, in nginx, to allow access to a "location" only to clients with a referrer that matches the current location name?

This is the scenario:

http://foooooo.com/bar.org/

http://foooooo.com/zeta.net/

etc etc

I want the contents of the bar.org location available only if the referrer is bar.org. The same goes for zeta.net

I know I can do this "statically", but there are a lot of those locations and I need to find a way to do this defining only one "dynamic" location.

Sorry for my bad english.

SOLUTION

I've solved this way:

location ~/([a-zA-Z0-9\.\-]*)/* {
    set $match "$1::$http_referer";
    if ($match !~* ^(.+)::http[s]*://[www]*[.]*\1.*$ ) {
        return 403;
    }
}
3
  • Is there any rule for the location, for example always the string in before the first slash(/). If yes, I have a solution.
    – srain
    Sep 20, 2013 at 2:29
  • Yes, locations are all in the same format. Sep 20, 2013 at 9:28
  • OK, I got you. Have a look at my answer. Any question please feel free to comment here.
    – srain
    Sep 20, 2013 at 12:38

2 Answers 2

18
location ~ ^/([a-zA-Z0-9\.\-]*)/(.*) {
    if ($http_referer !~ "^$1.*$"){
            return 403;
    }
}
1
  • 1
    Ok, you give me the right way to go, I'll edit my answer to include the code I've used. Sep 20, 2013 at 15:57
6
location /india/xxxxx.js {
    if ($http_referer !~ "http://domain.xxx/"){
            return 403;
    }
}

I solved my problem using slight changes, Thanks

2
  • underrated answer Feb 6, 2022 at 13:12
  • The only one actually does work correctly.
    – Teemu
    Jun 8, 2022 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.