I have a model News with an image and those News can be loaded via an JSON REST API. The server is signed with a certificate from an Authority and all request must be done with https.
My problem is, the ModelSerializer serialize the ImageField with http and not https. How do I change that ?
Here is an abstract of code and output example:
#myProject/models.py
class News(models.Model):
image = models.ImageField()
#myProject/serializers.py
class NewsSerializer(serializers.ModelSerializer):
class Meta:
model = News
fields = ('image')
#request for a news
https://myDomain/news/the-news-id-here/
#current output
{
"image": "http://myDomain/media/news/imageName.jpg"
}
#wanted output
{
"image": "https://myDomain/media/news/imageName.jpg"
}
Thanks David
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With