Running Gunicorn on both http and https
Asked Answered
S

4

12

When I start my Gunicorn service, I currently use this command to start it up:

gunicorn --certfile=/Projects/thebodyofchrist.us.crt --keyfile=/Projects/thebodyofchrist.us.key bodyofchrist.wsgi -b 0.0.0.0:443 -b 0.0.0.0:80 -w 10

For binding gunicorn to both http and https -- or setup apache2 to listen to http and redirect requests to https with existing parameters. I have hundreds of links to the http://example.com/sample/request and need it to automatically go to https://example.com/sample/request

gunicorn is hosting django.

Thanks for any help!

Skied answered 23/2, 2016 at 13:34 Comment(0)
C
10

Gunicorn is a very solid project, I hope they build it out someday with multiple port binding and command line switch to indicate SSL precedence.

When you finally get in production, you'll want to use the superior load balancing of Apache or Nginx.

But nothing prevents you (during development) from running some workers bound to port 80 and some workers bound to port 443 with keyfile and certfile set. You could then write the login link as an "absolute" url e.g. href="https://yoursite/login" after the login, they'd be using https urls.

#!/bin/sh
# put 8 workers as Daemon listening for HTTPS on 443
gunicorn -D -w 8 --certfile=/Projects/thebodyofchrist.us.crt --keyfile=/Projects/thebodyofchrist.us.key bodyofchrist.wsgi -b 0.0.0.0:443

# put 2 workers as Daemon listening for HTTP on port 80
gunicorn -D -w 2 bodyofchrist.wsgi -b 0.0.0.0:80
Collenecollet answered 14/11, 2017 at 14:7 Comment(4)
Now how do you redirect alll http traffic to https?Ettaettari
it depends on the framework you are using. For example if you use FastAPI or starlette. There is a Middleware that can do this: HTTPSRedirectMiddleware it just redirect using different schema and port number. Take a look on the code here maybe it can help you github.com/encode/starlette/blob/…Dehart
I am not sure if it is the best option to run a worker that only redirect request from http to https.Dehart
When it is running first line, will it every reach line 2?Herod
P
2

Multiple addresses can be bound. ex.:

gunicorn -b 127.0.0.1:8000 -b [::1]:8000 test:app

https://docs.gunicorn.org/en/stable/settings.html?highlight=bind#server-socket

so you can do this

gunicorn -b :80 -b :443 test:app
Participle answered 9/6, 2020 at 0:9 Comment(3)
wouldn't that use ssl on both 443 and 80 then?Tennies
This is wrong! Doesn't work with real https with certificates!Rustication
Yes, it would work for example.com and example.com:80, but not for example.comMctyre
J
1

Such support can be added inside gunicorn. As the moment it's not possible.

https://github.com/benoitc/gunicorn/issues/1466

Johny answered 31/5, 2017 at 14:57 Comment(0)
C
0

I would do this with a reverse proxy webservice not directly with uvicorn. So Trafaek and nginx come to mind.

Cytologist answered 17/2, 2023 at 23:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.