我有一个带有图像的模型新闻,这些新闻可以通过JSON REST API加载。服务器使用来自管理局的证书进行签名,所有请求必须使用https。
完成我的问题是,ModelSerializer使用http而非https序列化ImageField。我该如何改变?
以下是代码和输出示例的摘要:
#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"
}
由于 大卫
答案 0 :(得分:3)
请考虑在您的Nginx虚拟主机文件(即位于proxy_set_header X-Forwarded-Proto https;
内的conf文件)中添加/etc/nginx/sites-available/
。因此,简而言之,您的conf文件可能如下所示:
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;
}
最后,在添加proxy_set_header X-Forwarded-Proto https;
之后。您的REST API将被重定向到https。感谢dukeboy的评论。
答案 1 :(得分:0)
您可以像这样在nginx配置中执行此操作
server {
listen 80;
return 301 https://$host$request_uri;
}