简体   繁体   中英

How can I change http to https in django rest browsable api when I am using apache2 + gunicorn

The set up is

  • Apache2 as a reverse proxy
  • gunicorn serves django rest app
  • gunicorn + django app + mysql are in docker

Now the problem is in the browsable API, gunicorn serves the app at http://0.0.0.0:8000 but I use https://example.com/ as in Apache config. Every link in the browsable API is in the form of http://xxxxx .

When clicks the link, it redirects to http protocol, resulting in 404.

How can I tell gunicorn or django app to use https in the browsable API?

Edit:

gunicorn command: gunicorn -w 3 waxis_topup_api_django.wsgi -b 0.0.0.0:8000 --reload

setting.py is just an ordinary one without anything specific to http/https

apache config:

<VirtualHost *:443>
ServerAdmin xxx
ServerName example.com
Alias "/static" "/path/static"
ProxyPass "/static/" !
ProxyPass "/" "http://localhost:8000/"
ProxyPassReverse "/" "http://localhost:8000/"
ProxyPreserveHost On
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Port "443"
SSLEngine On
</VirtualHost>

Current workaround(solution?)

I can only think of this to force any http to be https, so even if there is a HTTP link in browsable API, it will be redirected to https by apache. I don't know if this is correct but it is more like a hack to me.

Here is my config in apache

<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>

Probably, one of the middleware web servers (apache or ngninx, or both) is not forwarding host, so Django is confused about the hostname it is serving on.

For apache, you need:

ProxyPreserveHost on

and for nginx you need:

proxy_set_header Host $host;

These will make apache and nginx forward the hostname and django will use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM