P
P
Pavel Dyukarev2019-02-21 23:33:48
Django
Pavel Dyukarev, 2019-02-21 23:33:48

nginx+https+django=404?

Guys, help)
There is a URL:

# стриминг mp3
    path('stream_mp3/<path:song>', views.stream_mp3, name='stream_mp3'),

There is a view:
# внимание! django dev сервер не поддерживает частичный ответ 206 поэтому работает только в nginx
def stream_mp3(request, song):
    song_name = song
    mp3_path = os.getcwd() + '/media/charge/music/' + song_name
    response = HttpResponse('', content_type="audio/mpeg", status=206)
    response['X-Accel-Redirect'] = '/media/charge/music/' + song_name
    response['X-Accel-Buffering'] = 'no'
    response['Content-Length'] = os.path.getsize(mp3_path)
    response['Content-Dispostion'] = "attachment; filename=" + mp3_path
    response['Accept-Ranges'] = 'bytes'
    return response

There is code in the template:
<audio controls onended="startNextTrack()">
    <source id="audio_sourse" src="{% url 'stream_mp3' song.name %}">
</audio>

The whole thing works fine on my computer: NGINX+DJANGO. Stream as it should. The player is working.
It's time to deploy, downloaded, configured the server, CONNECTED HTTPS and that's it:
Failed to https://batareika.app/listen/stream_mp3/bi2mojjroknrollmegapesnime.mp3 load resource: the server responded with a status of 404 (Not Found)

If you click on the link: , we get a 404 djanga response, where it is noteworthy that there is such a line:
Request URL:	http://batareika.app/media/charge/music/bi2mojjroknrollmegapesnime.mp3

I don’t really understand the device of communication between dzhanga and NGINX, but I think that the point is that the response in the view sends an http response to the template, and the browser waits for https.
I tried to redirect traffic in settings.py: As a result, the browser displays a window:
SECURE_SSL_REDIRECT = True
Страница недоступна
Сайт выполнил переадресацию слишком много раз.
Возможно, страница откроется, если удалить файлы cookie, установленные этим сайтом.

(I tried to delete cookies)
It completely confused me. Somehow, the link doubled back to itself during the redirection...
And all this despite the fact that without using HTTPS everything works normally.
Please note that of all the url addresses in the application, only those that are responsible for streaming have stopped working. The rest of the urls perfectly digested the transition to https, because nowhere on the site, except for the included fonts, I have absolute urls like http://.......big-bad.js. Only relative via {% url %} and {% static %}.
Here are the NGINX settings:
gunicorn.socket
[Unit]
  Description=gunicorn socket

  [Socket]
  ListenStream=/run/gunicorn.sock

  [Install]
  WantedBy=sockets.target

gunicorn.service
[Unit]
  Description=gunicorn daemon
  Requires=gunicorn.socket
  After=network.target

  [Service]
  User=root
  Group=www-data
  WorkingDirectory=/root/Batareika
  ExecStart=/root/Batareika/venv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          Batareika.wsgi:application

  [Install]
  WantedBy=multi-user.target

sites-available/Batareika
server {
      listen 80;
      server_name batareika.app;

      location = /favicon.ico { access_log off; log_not_found off; }
      location /static/ {
          root /root/Batareika;
          }

          location / {
          include proxy_params;
          proxy_pass http://unix:/run/gunicorn.sock;
          }
        }

nginx.conf
user root;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 1000;
        multi_accept on;
        use epoll;

}

http {

        ##
        # Basic Settings
        ##

         # Caches information about open FDs, freqently accessed files.
        open_file_cache max=200000 inactive=20s;
        open_file_cache_valid 30s;
        open_file_cache_min_uses 2;
        open_file_cache_errors on;

        # file upload timeout
        proxy_read_timeout 1200;

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 30;
        client_max_body_size 20M;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##
        # Compression.
        gzip on;
        gzip_min_length 10240;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css text/xml text/javascript application/x-javasc$
        gzip_disable "msie6";
        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

Please help with advice. So far, the ideas are at the level of some wild crutches.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
ky0, 2019-02-22
@ky0

You have three hundred thousand paths in different places, why so many? I didn’t master all the sheets, but I know that in the nginx config the location is incorrectly compiled or the path in the proxy_pass is not configured, which, apparently, is needed.
Try to start giving files simply from the root.

S
Sergey Nizhny Novgorod, 2019-02-22
@Terras

1) My application does not know about https at all, except for the NGINX config file and setting available hosts in settings.py
2) My filet config looks something like this (again, the nginx/gunicorn/django/virtual environment link):

server {
        listen 443 ssl;
    ssl_certificate /etc/ssl/your_domain.crt;      
        ssl_certificate_key /etc/ssl/your_domain.key;  
        server_name site.ru www.site.ru;
        
    gzip on;
    gzip_min_length 50;				
    gzip_comp_level 3;					
    gzip_types text/plain text/css text/javascript application/json application/x-javascript text/xml application/xml application/xml+rss;
    
    gzip_disable "msie6";

        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/user/site;
      access_log off;
      expires 15d; 
        }

        location  /media/ {
            root /home/user/site/;
      access_log off;
      expires 15d;
        }
        
        location  /robots.txt {
            root /home/user/site/faceset/static;
        }

        location / {
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_pass http://unix:/home/user/site/site.sock;
        }
    
    error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

    server {        
    listen 80;
    server_name site.ru;
    return 301 https://$host$request_uri;        
    }

those. the main entry point goes 443 from https, if it goes to port 80 via http, then I redirect the request to https.

P
Prog, 2019-02-22
@damprog

server {
listen 443;
server_name batareika.app;
ssl_certificate ....
ssl_certificate_key .....
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /root/Batareika;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 80;
server_name batareika.app;
return 301 https://$host$request_uri;
}
IMHO something like this
find 5 differences ))

L
latush, 2019-02-27
@latush

> proxy_pass http://unix:/run/gunicorn.sock;
this is where the problem comes in. https -> http
To avoid it, use uWSGI instead of Gunicorn and wsgi_pass instead of http_pass

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question