Nginx X-Accel-Redirect (AKA X-SendFile)
When Nginx serves as the front webserver for application servers, it wise to let Nginx serve static files. However, sometimes the static file to be served is determined dynamically and while it's possible to use regular 302 redirect it usually preferable to avoid it due to authentication, caching and other issues. The X-SendFile feature is an elegant solution to this problem and is implemented on Nginx as X-Accel-Redirect. The idea is to return a special header from the application to the webserver instead of the file itself and have the webserver catch the header, parse it to get the filename, then serve the file as the HTTP response. The location from which the file are served can be marked as "internal", thus keeping the files from being served without application authorization.
server {
...
location /virtual/private/static_files/ {
internal;
alias /srv/http/private/static_files/;
access_log /var/log/nginx/downloads.access_log;
}
The application should return X-Accel-Redirect header and the mime-type header for the file to download:
X-Accel-Redirect: /virtual/private/static_files/test.mp4
Content-Type: video/mp4
Nginx will then catch the X-Accel-Redirect header and serve
/srv/http/private/static_files/test.mp4, while squashing the X-Accel-Redirect header itself.
The
access_log directive is there because nginx will not log the internal sub-request by default.
Note: the trailing
/ is important, it must match the alias trailing slash for nginx to rewrite the path correctly.
--
AvishaiIshShalom - 21 Jul 2010