Use Nginx to proxy files from remote location using X-Accel-Redirect

Nginx supports X-Accel-Redirect for local files with no extra hassle, but what happens if you need to serve files located in some remote location like s3 and you don’t want to expose direct urls to the files? Sometimes you may want that to have control over stats or to keep an option to migrate to another file server without changing original urls.

Here is what you do:

Then in your application you need to set X-Accel-Redirect header with remote file hostname ( first part ) and URI (second part).

X-Accel-Redirect: /internal_redirect/

Potentially you could use the same idea for private files stored on S3. For that you would need to generate correct Authorization header

proxy_set_header Authorization "value";

which might be a little tricky, but possbile with perl support ( extract required tokens from instance metadata if you are using IAM roles, or use access keys passed to the instance somehow ).

Wake up, Neo... The matrix has you...

Join our growing UNDERGROUND MOVEMENT of Rain Makers. Just drop your email below and your life will never be the same again.

Feel free to reach out on Twitter, Facebook or Instagram.

I won't send you spam. Unsubscribe at any time. Powered by ConvertKit

One thought on “Use Nginx to proxy files from remote location using X-Accel-Redirect”

  1. Using njs (nginx js scripting) you can strip the whole $1$2 & co

    js_include x_proxypass.js;
    js_set $x_proxypass x_proxypass;

    location /x-proxypass/ {

    proxy_buffering off;
    proxy_pass $x_proxypass;

    With x_proxypass.js being

    function x_proxypass(r) {
    return String.bytesFrom(r.uri.replace(‘/x-proxypass/’, ”), ‘base64’);

    Then, your script should use X-Acccel-Redirect: “/x-proxypass/ “+ base64encode(“https://aws stuffs with all the pass”)

Leave a Reply

Your email address will not be published. Required fields are marked *