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
- fastapi runs on port 8000 with uvicorn
- react frontend runs on port 5000 with
npm start - axios base url is
localhost:8000
Everything works as expected and the axios calls return correct response.
Production setup
- fastapi runs on port 80 with gunicorn
- frontend built with
npm build - axios base url is
localhost - all request handled with nginx in frontend
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
- why is nginx redirecting the request even when I include
proxy_redirect off;in the conf file. - why does the redirect not return the correct response unless I remove
proxy_redirect off;