KMK
KMK

Reputation: 1499

Bypass Django to serve static files with Nginx

I'm trying to serve static files with Nginx, but it seems like Django takes control of the path and keeps giving a 404 because it's not a valid URL within the Django app.

Here's the Nginx server setup:

server {
    listen       443;
    server_name  localhost;

    client_max_body_size 500M;

    location /static/ {
        autoindex on;
        root /app/interfaces/web/static;
    }

    location / {
        uwsgi_pass django;
        include /app/interfaces/web/django/uwsgi_params;
    }
}

I have tried all following combinations:

When I try to access a file in the /static/ directory, I get the following 404 error from Django:

Page not found (404)

Request Method: GET Request

URL: https://172.16.6.158/static/test.css

Using the URLconf defined in django.urls, Django tried these URL patterns, in this order:

^ ^$ [name='index']

^history/

^config/

^admin/

The current path, static/test.css, didn't match any of these.

I also tried to set STATIC_URL in Django settings, but I don't think that should be neccessary since I'm trying to bypass Django. And it didn't make any difference anyway.

Does anyone know what I'm doing wrong? Do I need to change configuration somewhere else.

UPDATE

The Nginx access log gives the following error:

172.16.6.108 - - [11/Dec/2017:11:53:11 +0000] "GET /static/test.css HTTP/1.1" 404 3132 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" "-"

There's nothing in the error log.

Used setup:

location /static/ {
    alias /app/interfaces/web/static;
}

Upvotes: 0

Views: 795

Answers (1)

Naqib Hakimi
Naqib Hakimi

Reputation: 912

put this code inside server block

# Django media location 
 location  /media { alias /home/username/djangoproject/media; }

 location /static { alias /home/username/djangoproject/app/static;}
 # your Django project's static files `

and also you need to add static url and media url to urlpattern .google for serving static file in django

Upvotes: 2

Related Questions