Nginx raising 403 Forbidden when accessing Staticfiles in Django app on Digital Ocean
Asked Answered
B

1

7

having completed a django project on local development on my system, i followed the Digital Ocean tutorial to deploy a django app here Digital Ocean Django ASGI setup Tutorial.

i configured gunicorn according to the tutorials and all tests and confirmations are passed But when i loaded my site from its Public IP address the site loads without any styles or designs and no images...just as plain text (just html content)

my nginx configuration is as follows

server {
    listen 80;
    server_name XXX.XX.XXX.XX;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        alias /home/username/projectdir/staticfiles;
    }

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

and my django Project setting is as follows (section concerning static settings)

# The absolute path to the directory where collectstatic will collect static files for deployment.
STATIC_ROOT  = BASE_DIR / 'staticfiles'

# The URL to use when referring to static files (where they will be served from)
STATIC_URL = '/static/'

# extra places to find static filed outside static folder inside installed apps
STATICFILES_DIRS = [ BASE_DIR/"static" ]

MEDIA_ROOT = BASE_DIR/"media"

can any solution be suggested. i have seen all the other related stackoverflow questions that had similar issues but their solutions did not work for me . Thanks in Advance

Bitty answered 6/6, 2022 at 11:9 Comment(1)
I think it's a permission issue. The nginx user does not have permission to access the folder with staticfiles. I would do this sudo chmod 777 /home/username/projectdir/staticfiles to allow all users, including nginx, to access the staticfiles dirMentalism
T
7

It looks like a permission issue. I ran into the same issue, and I fixed it by granting the right permissions to the static folder specified in settings.py and in nginx.conf.

Additionally, in nginx.conf, I edited the user line by adding my current username + my group. Previously, I had: user nginx; I changed it to: user <my_username> <group>.

You can get your username by running whoami in your terminal. You can use id -g -n $whoami to find your group.

Hope it helps.

Trews answered 14/5, 2023 at 15:12 Comment(3)
Spent like 2 days on fixing this issue. Found different solutions on different blogs/forums. But only your solution helped me. Thanks a lot.Truckage
this worked for me too! changed /etc/nginx/nginx.conf, the user line from user www-data; to user <my username>, in settings.py i had static_root = base_dir / "static" and in /etc/nginx/sites-available/<project> /static/ root /home/<my_username>/<project_name>; nothing else worked , thanks buddy!Purchasable
After hours of debugging and browsing finally this worked for me too. Thanks a lot!Heikeheil

© 2022 - 2024 — McMap. All rights reserved.