问题
I have just run across an issue where setting response.headers['Content-Length']
in a Rails 3.2.2 application causes Nginx to throw a "502 Bad Gateway" error.
I have an action in a controller that uses the send_data
method to send raw JPEG data contained within a variable. Before, I had a problem with some browsers not downloading the entire image being sent and discovered that no Content-Length header is being sent, so I decided to use the .bytesize
property of the variable containing the JPEG data as the Content-Length.
This works fine in development (using Unicorn) and there is now a Content-Length header where there wasn't one before, but in production where I'm using Nginx and Passenger, I get the afore-mentioned 502 Bad Gateway. Also, in the Nginx error log, I see:
[error] 30574#0: *1686 upstream prematurely closed connection while reading response header from upstream
There are no matching entries in the Rails production log, which tells me the application is fine.
I've commented out the line where I set the Content-Length header, and the problem went away. I'm still testing whether I actually need to send a Content-Length header, but meanwhile, I thought I might post this out of curiosity to see if anyone has any thoughts.
回答1:
AHA! I had to convert the size to a string by adding the .to_s
method. So, my final result is
response.headers['Content-Length'] = photo_data.bytesize.to_s
send_data photo_data, :type => :jpg, :filename => 'file_name.jpg', :disposition => 'attachment'
So, it would seem that it is okay to send the Content-Length
header on Nginx/Passenger, but Passenger chokes if it's not explicitly a string.
来源:https://stackoverflow.com/questions/14441118/passenger-3-0-17-nginx-1-2-4-content-length-header-502-bad-gateway