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.
You could use HTTPSRedirectMiddleware
. This would enforce "that all incoming requests must either be https
or wss
. Any incoming requests to http
or ws
will be redirected to the secure scheme instead`.
from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
app = FastAPI()
app.add_middleware(HTTPSRedirectMiddleware)
@app.get("/")
async def main():
return {"message": "Hello World"}