brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: X-Accel-Redirect lets your app check access and nginx send the file

Nginx
~/tips/tip-nginx-x-accel-redirect

location /protected/ {

Lets a backend approve a download and hand the actual file transfer to nginx.

Private downloads usually need a permission check in the app. Streaming a big file through PHP or Python just to do that check ties up an app worker for the whole transfer. nginx can take over after the check.

location /protected/ {
    internal;
    root /srv;
}
location /download/ {
    proxy_pass http://127.0.0.1:8081;
}

The app handles /download/..., checks the user, and answers with an empty body and a header such as X-Accel-Redirect: /protected/report.pdf. nginx sees the header, drops the app’s response, and serves the file from /srv/protected/report.pdf itself, with range requests and sendfile. The app worker is free right away.

The internal line is the security part. It makes the location reachable only through such a redirect, so a direct request for /protected/report.pdf gets a 404. I’d test both paths: the download through the app should deliver the full file, and the direct link should get a 404.

A few details. The path in the header is a URI that nginx matches against its locations, not a file path on disk. You can add headers like X-Accel-Limit-Rate or X-Accel-Buffering to the same response. Many frameworks have support built in, often called “send file” with an nginx option. Don’t forget to set Content-Disposition in the app when the file should download with a nice name.

Further reading: X-Accel-Redirect (proxy_ignore_headers), internal

Going deeper: 🛜 Guide: AdGuard Home + Tailscale (Secure Split-Horizon DNS)

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link