Nginx - Allow access to folder directory only by referring URL

front-end web developer here. Sorry in advance.

My company wants to store new builds of our software on our web server, running Nginx, provided by WP Engine.

The file path for these builds would be company.com/downloads/file.zip. We want to restrict access to files in this folder unless they come from a specific referring URL that sits behind a login gate for our customers.

  • If user clicks link to any file inside /downloads/ from allowed referrer, user gets file
  • If user clicks link from any other source, return 404 or redirect to homepage
  • If empty referrer or direct access attempt, return 404 or redirect to homepage

I've found a resource on preventing hotlinking for images (we'll be dealing with .zip files), which might work for me, but I need help with the syntax of this language. There's probably a bunch wrong with it.

location ~ /downloads/$ {
valid_referers none blocked ~.allowed_domain.com;
if ($invalid_referer) {
return 404;
}
}

WP Engine doesn't allow me to add Nginx code myself, so I'll have to send them the code I want them to implement. If anyone knows how to do this and can help me out, I'd really appreciate it!

1
задан 22 February 2017 в 22:14
2 ответа

Другая возможность - использовать заголовок X-Accel . Я не знаю вашего варианта использования, поэтому он может не подойти.

X-Accel - это заголовок, специфичный для nginx. Вы можете использовать этот заголовок в своем PHP-скрипте - например, заголовок («X-Accel-Redirect: /private-downloads/magic.iso") Когда nginx распознает этот заголовок, он будет серверным содержимым файла magic.iso , расположенный в / data / private-downloads .

Итак, ваша задача - подготовить download.php , который проверяет авторизацию и отвечает либо заголовком X-Accel , либо перенаправляет на экран входа в систему.

Определение / private-downloads / в nginx.conf

location /private-downloads/ {
    internal;    # this
    alias /data/private-downloads;
    # this should be located outside of HTTP server root
}

Для получения дополнительной информации, пожалуйста, проверьте вопросы x-Accel при сбое сервера. 1

1
ответ дан 3 December 2019 в 23:33

Можно использовать директиву valid_referers nginx. ( nginx doc )

location /downloads/ {
    alias /var/www/downloads;
    valid_referers  www.example.me ;

if ($invalid_referer) {
        return 404;
    }
}

Я лично никогда не пробовал это в продакшене, потому что я предпочитаю использовать заголовок X-Accel . Вы можете подтвердить своего пользователя в сценарии PHP, а затем отправить заголовок nginx X-Accel. Заголовок попросит nginx передать статические файлы на сервер nginx.

0
ответ дан 3 December 2019 в 23:33

Теги

Похожие вопросы