Streaming mp3 files in Django through Nginx
<p>I have a website based on Django framework. I am running website via Nginx webserver (uWSGI,Django,Nginx). I want to stream mp3 files on my website with Accept-Ranges header. I want to serve my mp3 files with Nginx. I need my API to look like this</p>

<pre><code>http://192.168.1.105/stream/rihanna
</code></pre>

<p>This must return mp3 file with partial download (Accept-Ranges).
My mp3 files are stored in : /home/docker/code/app/media/data/
When I run the server with these configurations and browse to 192.168.1.105/stream/rihanna , Django returns 404.</p>

<p>My Nginx conf:</p>

<pre><code># mysite_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
server unix:/home/docker/code/app.sock; # for a file socket
# server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
# the port your site will be served on, default_server indicates that this server block
# is the block to use if no blocks match the server_name
listen      80 default;
include /etc/nginx/mime.types;
# the domain name it will serve for
server_name .example.com; # substitute your machine's IP address or FQDN
charset     utf-8;

# max upload size
client_max_body_size 75M;   # adjust to taste

# Django media
location /media  {
    autoindex       on;
    sendfile        on;
    sendfile_max_chunk      1024m;
    internal;
    #add_header X-Static hit;
    alias /home/docker/code/app/media/;  # your Django project's media files - amend as required
}
location /static {
    alias /home/docker/code/app/static/; # your Django project's static files - amend as required
}

# Finally, send all non-media requests to the Django server.
location / {

    uwsgi_pass  django;
    include     /home/docker/code/uwsgi_params; # the uwsgi_params file you installed
    }
}
</code></pre>

<p>My views.py :</p>

<pre><code>def stream(request, offset):
     try:

            mp3_path = os.getcwd() + '/media/data/' + offset + '.mp3'
            mp3_data = open(mp3_path, "r").read()



except:
    raise Http404()





response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = mp3_path
response['X-Accel-Buffering'] = 'no'
response['Content-Length'] = os.path.getsize(mp3_path)
response['Content-Dispostion'] = "attachment; filename=" + mp3_path
response['Accept-Ranges'] = 'bytes'
</code></pre>

<p>I want Nginx serve this files. And I really need Accept-Ranges enabled.</p>

<p>My Settings.py :</p>

<pre><code># Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR =   os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/


DEBUG = True

ALLOWED_HOSTS = ['localhost', '127.0.0.1', '192.168.1.105', '0.0.0.0']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

 MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'beats.urls'

 TEMPLATES = [
    {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')]
    ,
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'beats.wsgi.application'

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = os.path.join(BASE_DIR, 'media/')




# Database


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   }
}


# Password validation


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME':   'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]



LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True



STATIC_URL = '/static/'
</code></pre>

<p>My problem is: It doesn't work, and Django return 404 Error webpage.</p>

<p>First of all, I did not copy the Nginx configuration file to the available-sites path. And because of it,It didn't work.
And in my views.py :</p>

<pre><code>response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = mp3_path
</code></pre>

<p>these 2 lines must be changed to:</p>

<pre><code>response= HttpResponse('', content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = '/media/data/' + offset + '.mp3'
</code></pre>

<p>I hope it helps anybody else who has this problem.</p>

python django nginx http-headers uwsgi