CodexBloom - Programming Q&A Platform

Getting CORS implementing FastAPI when deploying behind Nginx

👀 Views: 35 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
fastapi nginx cors web-services python

I need some guidance on I'm working with CORS (Cross-Origin Resource Sharing) issues when trying to access my FastAPI application from a frontend hosted on a different domain... My FastAPI version is 0.68.0, and I'm using Nginx as a reverse proxy. The response from the server is showing the following behavior: `Access-Control-Allow-Origin` header contains multiple values 'http://example.com, *' but only one is allowed. I've already added the CORS middleware like this: ```python from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["http://example.com"], # Frontend domain allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE"], allow_headers=["*"], ) ``` Despite this, I still keep getting the CORS behavior. On the Nginx side, I have the following configuration: ```nginx server { listen 80; server_name api.example.com; location / { proxy_pass http://localhost:8000; 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; add_header 'Access-Control-Allow-Origin' 'http://example.com'; add_header 'Access-Control-Allow-Credentials' 'true'; } } ``` I tried removing the `add_header 'Access-Control-Allow-Origin'` line from the Nginx config, but that didn't help either. I also confirmed that no other middleware or settings are conflicting with CORS. What could be causing this scenario, and how can I resolve it? Any insights would be appreciated! My development environment is Ubuntu 22.04. Any suggestions would be helpful.