Reputation: 89
I am attempting to develop a web app with nginx and fastapi and react. These are all new to me.
Regarding the fastapi, I have a main FastAPI
that has a login route. I have added additional routes with APIRouter
class and FastAPI.include_router
method. I refered to this documentation
Development setup
npm start
localhost:8000
Everything works as expected and the axios calls return correct response.
Production setup
npm build
localhost
I based the following nginx conf file on this documentation
# conf file for server
# proxy pass for api requests
upstream api {
server backend;
}
# main server for app
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/frontend;
error_log /var/log/nginx/frontend;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
proxy_redirect off;
proxy_pass http://api;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
Note that I am using docker compose and have a backend service and a frontend service.
With this configuration the login route works correctly, but the routes added via FastAPI.include_router
return HTTP 307 redirect and the response header shows requested url as http://api/api/path/to/route
instead of http://localhost/api/path/to/route
. So it appears that nginx successfully proxy passes requests for a route directly in the main fastapi app module but redirects to the wrong url for requests to routes added with app.include_router
. According to this reference, I should have proxy_redirect off;
in the /api
location block, but if I remove this line, then nginx redirects the request and returns the correct response.
question
proxy_redirect off;
in the conf file.proxy_redirect off;
Upvotes: 5
Views: 2474
Reputation: 5
I think the issue might not be with Nginx, but with how FastAPI handles trailing slashes
If you define the routes as "api/route/" and try to reach "api/route", FastAPI will attempt to redirect to "api/route/" (and vice-versa for "api/route" and "api/route/")
You can disable this behaviour with a flag in FastAPI
app = FastAPI(redirect_slashes=False)
Nginx proxy redirect with FastAPI routers
https://fastapi.tiangolo.com/reference/fastapi/#fastapi.FastAPI--example
Upvotes: 0