带有ImageField和HTTPS的Django ModelSerializer

svdrlsy4  于 2022-11-18  发布在  Go
关注(0)|答案(3)|浏览(148)

我有一个带有图片的新闻模型,这些新闻可以通过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"
}

谢谢大卫

umuewwlo

umuewwlo1#

请考虑将proxy_set_header X-Forwarded-Proto https;添加到Nginx虚拟主机文件中,即位于/etc/nginx/sites-available/中的conf文件。因此,简而言之,您的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。

mw3dktmi

mw3dktmi2#

您可以在nginx config中执行此操作,如下所示

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

pb3s4cty3#

我也遇到了同样的问题,我的解决方法是在django的settings.py文件的MEDIA_URL中添加完整的https网址:
修改前:

MEDIA_URL = '/media/'

修改后:

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

不需要调整nginx配置。

相关问题