[Solved]-Django ModelSerializer with ImageFIeld and HTTPS

4👍

Please consider adding proxy_set_header X-Forwarded-Proto https; inside of your Nginx virtual host file i.e conf file located within /etc/nginx/sites-available/. So, in a nutshell, your conf file may look like this:

server {
    listen   443 ssl;
    server_name example.com www.example.com;
    root /var/www/html/static_files/;

    client_max_body_size 4G;
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto https;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    access_log /home/user/API/logs/nginx-access.log;
    error_log /home/user/API/logs/nginx-error.log;

    location /api/ {
        proxy_pass http://127.0.0.1:8000/api/;
    }

    location /media/ {
        proxy_pass http://127.0.0.1:8000/media/;
    }

    # Error pages
    # error_page 500 502 503 504 /home/user/API/500.html;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}

In conclusion, after adding proxy_set_header X-Forwarded-Proto https;. Your REST API will be redirected to https. Credit to dukeboy for his comment.

👤Brian

0👍

You can do this in nginx config, like this

server {
    listen         80;
    return 301 https://$host$request_uri;
}
👤Ali

0👍

I faced the same problem, my work around was to add the full url with https in the MEDIA_URL, inside django’s settings.py file:

Before modification:

MEDIA_URL = '/media/'

After modification:

MEDIA_URL = 'https://www.my-app.com/media/'

No need to tweak nginx configs.

Leave a comment