I’m trying to run a fastapi app with SSL.
I am running the app with uvicorn.
I can run the server on port 80 with HTTP,
if __name__ == '__main__':
uvicorn.run("main:app", port=80, host='0.0.0.0', reload = True, reload_dirs = ["html_files"])
To run the port with HTTPS, I do the following,
if __name__ == '__main__':
uvicorn.run("main:app", port=443, host='0.0.0.0', reload = True, reload_dirs = ["html_files"], ssl_keyfile="/etc/letsencrypt/live/my_domain/privkey.pem", ssl_certfile="/etc/letsencrypt/live/my_domain/fullchain.pem")
How can I run both or simply integrate https redirect?
N.B: This is a setup on a server where I don’t want to use nginx, I know how to use nginx to implement https redirect.
3
Answers
Run a subprocess to return a redirect response from one port to another.
main.py:
https_redirect.py:
Use
HTTPSRedirectMiddleware
. This will enforce redirection tohttps
on any incoming requests.I think you can redirect all traffic from port 80 to port 443 on the OS level using.
For example, on Ubuntu, by run in the terminal: