Serving 206 Byte-Range through Nginx, Django

JamieT picture JamieT · Jan 30, 2013 · Viewed 7.3k times · Source

I have Nginx serving my static Django files which is being run on Gunicorn. I am trying to serve MP3 files and get them to have the head 206 so that they will be accepted by Apple for podcasting. At the moment the audio files are in my static directory and are served straight through Nginx. This is the response i get:

    HTTP/1.1 200 OK
    Server: nginx/1.2.1
    Date: Wed, 30 Jan 2013 07:12:36 GMT
    Content-Type: audio/mpeg
    Content-Length: 22094968
    Connection: keep-alive
    Last-Modified: Wed, 30 Jan 2013 05:43:57 GMT

Can someone help with the correct way to serve mp3 files so that byte-ranges will be accepted.

Update: This is the code in my view that serves the file through Django

    response = HttpResponse(file.read(), mimetype=mimetype)
    response["Content-Disposition"]= "filename=%s" % os.path.split(s)[1]
    response["Accept-Ranges"]="bytes"
    response.status_code = 206
    return response

Answer

Michał Kupisiński picture Michał Kupisiński · Jan 30, 2013

If you want to do this only in nginx then in your location directive which is responsible for serving static .mp3 files add those directives:

# here you add response header "Content-Disposition"
# with value of "filename=" + name of file (in variable $request_uri),
# so for url example.com/static/audio/blahblah.mp3 
# it will be /static/audio/blahblah.mp3
# ----
set $sent_http_content_disposition filename=$request_uri;
    # or
add_header content_disposition filename=$request_uri;

# here you add header "Accept-Ranges"
set $sent_http_accept_ranges bytes;
# or
add_header accept_ranges bytes;

# tell nginx that final HTTP Status Code should be 206 not 200
return 206;

I hope it will give you some help.