Home > OS >  How to make a custom 404 page?
How to make a custom 404 page?

Time:04-09

I am making a rick roll site for discord and I would like to redirect to rick roll on 404 response status codes.

I've tried the following, but didn't work:

 @app.exception_handler(fastapi.HTTPException)
 async def http_exception_handler(request, exc):
     ...

CodePudding user response:

You would need to create a middleware and check for the status_code of the response. If it is 404, then return a RedirectResponse. Example:

from fastapi.responses import RedirectResponse

@app.middleware("http")
async def redirect_on_not_found(request: Request, call_next):
    response = await call_next(request)
    if response.status_code == 404:
        return RedirectResponse("https://fastapi.tiangolo.com")
    else:
        return response
  • Related