Skip to content Skip to sidebar Skip to footer

Django - Problems With Static Files When Running In Subpath

I have django app running in subpath example.com/api/. Most of it is rest API (I use django-rest-framework), and all requests are working correctly. But static files has wrong path

Solution 1:

If you proxy_pass a location in Nginx and add a URI to your proxy_pass directive you are telling Nginx to remove that from the original request URL and replace that part of the request URI with your proxy_pass URI. So this:

location /api/ {
    proxy_pass            http://localhost:8000/;

Tells Nginx that a request to example.com/api/path/to/whatever/ should be proxied to http://localhost:8000/path/to/whatever/

If you want the original unaltered request URI passed to the proxy then remove the / from the end of the proxy_pass directive

Solution 2:

This is a known issue in Django.

Expected behavior

Outside world (nginx\uwsgi\whatever) should have SCRIPT_NAME header (which would be equal to /api in your case) and forward it to Django.

Django should respect this header and add it for the URLs generated with {%url ... %} tag (which it does already) AND for static file links generated with {% static ... %} (which does not work, see mentioned issue).

To workaround this you can append prefix directly to STATIC_URL: STATIC_URL = '/api/static'... But this is a dirty hack, I agree. The proper way is to to have it fixed on Django side.

Also see https://stackoverflow.com/a/57009760/1657819, may be a bit related

Solution 3:

add this code to your nginx configuration:

location /static/ {
    alias /path/static/;
}

you should define the location of static files, in order to read it.

Post a Comment for "Django - Problems With Static Files When Running In Subpath"