skip to Main Content

I have been trying to solve this error for almost 13 hours, looking for thousands of stackoverflow questions and questions of other communities but I still can’t find the answer.
What I’m trying to do is solve nginx not serving static files.
as I said on the top, I tried thousands of answers and none of them seem to work for me.

I post only the scripts in nginx /sites-available/ because I think that is the primary script for this question.

server {
        listen 80;
        server_name localhost 127.0.0.1;

        location = /favicon.ico { access_log off; log_not_found off; }
        location /static {
                autoindex on;
                alias /home/ngx/pid/static/;
        }

        location / {
                include proxy_params;
                proxy_pass http://unix:/run/gunicorn.sock;
        }
}

I use gunicorn for loading django and also the frontend is made with react so without main.js I can’t do anything.
ngx is not a default user – I made it and also I followed this DigitalOcean tutorial.(Although I didn’t follow all of them – I edited after reading answers by other people.

Directory
/home/ngx/pid (django root)
        ㄴ diary (project root - settings.py, wsgi.py etc.)
        ㄴ djenv (virtualenv)
        ㄴ frontend (react)
        ㄴ manage.py
        ㄴ static (made by python3 manage.py collectstatic)

Error URL:
http://example.com/static/css/index.css
http://example.com/static/frontend/main.js <- React JS file

Error Code: 404 Not Found

2

Answers


  1. Chosen as BEST ANSWER

    I didn't mention that I am using DDNS and port-forwarding my Linux machine to get access from the outside internet.
    and I am also new to Nginx I didn't know that I had to add the site domain name at server_name.
    I added my site domain to server_name and now it works properly.
    It is similar to ALLOWED_HOSTS in Django.
    Thanks to everyone who helped me.

    The code that worked

    server {
            listen 80;
            server_name localhost 127.0.0.1 MYSITE_DOMAIN;
    
            location = /favicon.ico { access_log off; log_not_found off; }
            location /static/ {
                    root /home/ngx/pid;
            }
    
            location / {
                    include proxy_params;
                    proxy_pass http://unix:/run/gunicorn.sock;
            }
    }
    

  2. I think you should try the following configuration:

    location /static/ {
                    root /home/ngx/pid;
            }
    
    

    Alias is for defining a replacement for the specified location, probably the reason it’s not working.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search