A
A
Alexey Naimushin2017-04-03 12:03:04
Nginx
Alexey Naimushin, 2017-04-03 12:03:04

How to distribute static and protect files from direct download in Nginx and Node.js?

Good afternoon, dear experts!
There is a site with training courses that works in conjunction with Nginx and Node.js.
Nginx distributes static from two directories: public , which contains styles, scripts, etc. and the data directory , which contains the lesson materials themselves (video lectures, slides, etc.) and which should be available only after authorization.
Several problems have arisen:
1. If you remove the lines from the Node.js server

app.use(express.static(path.join(__dirname, 'public'))),
that is, remove the distribution of statics through Node.js, then the request for files is returned with a 404 error. Although, as I understand it, they should be distributed by Nginx and not depend on the node?
2. How to configure Nginx config to block files from direct download?
I tried to write the following in the config,
location /files {
        internal;
        alias /data;
    }

However, in this case, the response comes with either 404 or (canceled) and the Provisional headers are shown header.
Addendum
add_header 'Access-Control-Allow-Origin' "$http_origin"
doesn't help either.
Thanks in advance for your help!
PS. Full Nginx config
server {
    server_name 127.0.0.1;
    root D:/Server/local/sites/local;

    location / {
        proxy_pass http://127.0.0.1:3000/;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }

    location = /favicon.ico {
        access_log     off;
        log_not_found  off;
    }

    location /public {
    	allow all;
    }


    location /files {
        internal;
        alias /data;
    }

    error_log D:/Server/nginx/logs/local_error.log;
    access_log D:/Server/nginx/logs/local_access.log;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kostnikolas, 2017-04-03
@kostnikolas

Use X-Accel-Redirect.
Description:
www.opennet.ru/base/net/nginx_x_accel_redirect.txt.html
In short, nginx sends a request to download a file to Node.js, if the user is allowed to download, then the node responds with the X-Accel-Redirect header:'/ static/file.jpg'. Otherwise, we return 404.
Having received the X-Accel-Redirect from Node.js , nginx starts serving the file to the user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question