jkarimi
jkarimi

Reputation: 1267

django+gunicorn+nginx 404 serving static files

I have django+gunicorn+nginx running on 192.168.1.81:3000. The web app will not serve any static files; it returns a 404 error. This suggests that there is a problem with the nginx virtual server config file. I have tried several solutions offered on stack overflow with no success. What is wrong with the nginx virtual server file?

upstream app_server {
        server unix:/home/pi/door_site/gunicorn.sock fail_timeout=0;
}

server {
        listen 80;
        server_name 192.168.1.81;
        client_max_body_size 4G;
        access_log /home/pi/door_site/logs/nginx-access.log;
        error_log /home/pi/door_site/logs/nginx-error.log;
        location /static/ {
                alias /home/pi/door_site/static/;
        }

        location / {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                if (!-f $request_filename) {
                        proxy_pass http://app_server;
                        break;
                }
        }
}

Upvotes: 1

Views: 3712

Answers (3)

user4981459
user4981459

Reputation:

I my case it was a permission issue on static directory and it worked after assigning proper permissions.

Upvotes: 0

bob
bob

Reputation: 751

try this config using server root and try_files

upstream app_server {
    server unix:/home/pi/door_site/gunicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name 192.168.1.81;
    client_max_body_size 4G;
    access_log /home/pi/door_site/logs/nginx-access.log;
    error_log /home/pi/door_site/logs/nginx-error.log;

    root /path/to/root # place your static directories in root i.e /path/to/root/static

    location / {
        try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}

This will try to find your static file and then move onto your app server.

Make sure nginx is running as the right user to access your files and that your static files permissions are correctly set perhaps with:

chmod -R u=rwX,g=rwX,o=rX static_dir

Upvotes: 0

Alexander Borshak
Alexander Borshak

Reputation: 21

In Nginx virtual server conf file inside server section you need to add to location sections for Nginx can serve files in /static/ and /media/ folders:

location /media {
    alias /path/to/your/folder/media;
}

location /static {
    alias /path/to/your/folder/static;
}

After that test Nginx configuration:

sudo nginx -t

and reload Nginx:

sudo nginx -s reload

(or restart - sudo /etc/init.d/nginx restart )

Upvotes: 2

Related Questions