Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: Prevent direct access to static files

Tags:

nginx

I've been searching for a while now but didn't manage to find anything that fits my needs. I don't need hotlinking protection, as much as I'd like to prevent people from directly accessing my files. Let's say:

My website.com requests website.com/assets/custom.js, that'd work,but I'd like visitors which directly visit this file to get a 403 status code or something. I really have no idea if it's possible, and I don't have any logical steps in mind..

Regards !

like image 459
Eduard Avatar asked Jul 06 '14 00:07

Eduard


2 Answers

You can use nginx referer module: http://nginx.org/en/docs/http/ngx_http_referer_module.html. Something like this:

server {
    listen 80;
    server_name website.com;
    root /var/www/website.com/html ;
    location /assets/ {
        valid_referers website.com/ website.com/index.html website.com/some_other_good_page.html ;
        if ($invalid_referer) {
            deny all;
        }
    }
}

This config guard assets directory. But remember, that not guaranteed and worked only for browser - any body can emulate valid request with curl or telnet. For true safety you need use dynamic generated pages with dynamic generated links.

You do not need to create the variable $invalid_referer as this is set by the nginx module.

like image 148
mr_tron Avatar answered Nov 11 '22 16:11

mr_tron


If you nginx powered development instances are showing up in Google search results, there is a quick and easy way to prevent search engines from crawling your site. Add the following line to the location block of your virtualhost configuration file for the block that you want to prevent crawling.

add_header  X-Robots-Tag "noindex, nofollow, nosnippet, noarchive";
like image 34
James M Avatar answered Nov 11 '22 17:11

James M