Below the nginx configuration i use for my FastAPI application.
The static files are served directly from the FastAPI static contents and dont have any static files under the nginx server.
My frontend and backend application works fine without any issues, however when i try to do reload / refresh from the webpage i am getting 404 error, for which i tried configuring the try_files (try_files $uri $uri/ http://frontend_app/;), but couldn't load the web page itself.
nginx.conf
worker_processes auto;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
client_max_body_size 100M;
upstream frontend_app {
server 127.0.0.1:8000;
}
# Upstream configuration for APIs
upstream backend_api {
server 127.0.0.1:8000;
}
# HTTPS configuration
server {
listen 443 ssl;
http2 on;
ssl_certificate /opt/bitnami/nginx/conf/bitnami/certs/server.crt;
ssl_certificate_key /opt/bitnami/nginx/conf/bitnami/certs/server.key;
error_log /opt/bitnami/nginx/logs/error.log debug;
access_log /opt/bitnami/nginx/logs/access.log;
# Proxy API calls for backend API
location /api/acm/ {
proxy_pass http://backend_api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Redirect HTTP to HTTPS
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
# Default location handling for root path
location / {
proxy_pass http://frontend_app/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
My FastAPI configuration for serving the static files.
app.mount("/am/", StaticFiles(directory=f"{path_to_static_dir}/application/dist", html=True))
@app.get("/")
async def root():
from fastapi.responses import RedirectResponse
return RedirectResponse(url="/am/")
Can you help me what configuration am i missing ?
frontend_appandbackend_apiupstream definitions identical? Did you try to emulate the React Router approach? Thetry_filesdirective neither has a syntax that allows specifying a foreign server URL as a fallback nor is it applicable for anything other than serving local static files. I can give you an example of an nginx config implementing the same logic (making a second "root" request to the upstream if the first request results in an HTTP404 Not Founderror), though I don't think this will solve the issue you're facing.