Nginx: Is post_action skipped when Rails returns a X-Accel-Redirect header is used?

384 Views Asked by At

The post_action in the config for my Nginx 1.4.2 instance is not firing (or does not appear to be). I'm wondering if it is because Rails is returning a X-Accel-Redirect header. The ultimate goal is track when downloads hosted on S3 have completed.

Step 1: The request hits nginx at http://host/download/...

location ~ /download/ {
  proxy_pass http://rails-app-upstream;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  post_action @finished;
}

Step 2: After authenticating the request for the download file and marking the start of the download in the database, Rails returns the request with the following headers:

{ 
   'X-Accel-Redirect' => '/s3-zip/my-bucket.s3.amazonaws.com/downloads/0001.jpg`
   'Content-Disposition' => "attachment; filename=download.jpg",
   'X-Download-Log-Id' => log.id.to_s,
   'X-Download-Mem-Id' => log.membership_id.to_s
}

Step 3: Nginx catches the x-accel-redirect header and hits this location that is defined:

location ~ "^/s3-zip/(?<s3_bucket>.[a-z0-9][a-z0-9-.]*.s3.amazonaws.com)/(?<path>.*)$" {
  # examples:
  #   s3_bucket = my-bucket.s3.amazonaws.com
  #   path = downloads/0001.mpg
  #   args = X-Amz-Credentials=...&X-Amz-Date=...
  internal;

  access_log /var/log/nginx/s3_assets-access.log main;
  error_log /var/log/nginx/s3_assets-error.log warn;

  resolver 8.8.8.8 valid=30s; # Google DNS
  resolver_timeout 10s;

  proxy_http_version 1.1;
  proxy_set_header Host $s3_bucket;
  proxy_set_header Authorization '';

  # remove amazon headers
  proxy_hide_header x-amz-id-2;
  proxy_hide_header x-amz-request-id;
  proxy_hide_header Set-Cookie;
  proxy_ignore_headers "Set-Cookie";

  # no file buffering
  proxy_buffering off;

  # bubble errors up
  proxy_intercept_errors on;

  proxy_pass https://$s3_bucket/$path?$args;
}

Missed Step: The following location called by the post_action in Step 1 is never fired. Is this because of the x-accel-redirect header, or because Step 3 uses a proxy_pass, or something else? This last location calls the rails route again once nginx has completed the request to mark the download as completed.

location @finished {
  internal;

  rewrite ^ /download/finish/$sent_http_x_download_log_id?bytes=$body_bytes_sent;
}
0

There are 0 best solutions below