Answer the question
In order to leave comments, you need to log in
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? location /files {
internal;
alias /data;
}
add_header 'Access-Control-Allow-Origin' "$http_origin"
doesn't help either. 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
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 questionAsk a Question
731 491 924 answers to any question