How to make Django's Browsable API Renderer generate correct URLs with an /api/ prefix when behind Nginx?
I'm deploying a Django application using the Django Rest Framework (DRF) on a server behind Nginx. The application is accessible via https://my-site.com/api/ where /api is routed to the Django application. However, when I access the API's browsable UI at https://my-site.com/api/locations, everything works fine. But when I try to click the "Get JSON" button from the UI, it generates an incorrect URL: /locations?format=json instead of the correct /api/locations?format=json. Or when i try to POST it posts to /locations instead of /api/locations
The issue is that the DRF Browsable API Renderer seems to be constructing the URLs as if the app is running directly under the root path (/), but in reality, it's running under /api/ on the server due to Nginx routing.
# Proxy requests to the Django backend (API)
location /api/ {
proxy_pass http://127.0.0.1:8000/;
proxy_set_header X-Script-Name /api; # Tell Django it's running under /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;
}
What I'm Looking For: A solution to make the Django Browsable API Renderer correctly generate URLs with the /api/ prefix when behind Nginx.