Permission denied /media files Django Nginx setup

I followed this tutorial:

https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04

Everything is working (static files are served etc) but by user uploaded media files show a ‘permission denied’ when trying to access the image:

2023/01/21 09:50:01 [error] 12912#12912: *266 open() "/home/hvn/intranet/intranet/media/images/werkstujk_1_Far44Li.2e16d0ba.fill-322x247-c100.jpg" failed (13: Permission denied), client: xxx.xxx.xxx.xxx, server: xxxxx.net, request: "GET /media/images/werkstujk_1_Far44Li.2e16d0ba.fill-322x247-c100.jpg HTTP/1.1", host: "www.xxxxxx.net", referrer: "https://www.xxxxx.net/blogs/"

I’m using wagtail as cms system.

The Gunicorn socket is running under user ‘hvn’ and group ‘www-data’.

The directory and filepermissions are like:

750 for dirs and 644 for files:

ll | grep media
drwxr-xr-x  5 hvn www-data 4096 Jan 17 22:36 media/

-rw-r--r-- 1 hvn www-data  33857 Jan 21 00:24 werkstujk_1_Far44Li.2e16d0ba.fill-322x247-c100.jpg

My nginx config file is serving the media folder:

location /media/ {
        root /home/hvn/intranet/intranet;
    }
/etc/nginx/sites-enabled/xxx.xx                                               
server {
    server_name xxx.xx *.xxx.xx;

location = /favicon.ico { access_log off; log_not_found off; }
    location /collectstatic/ {
        root /home/hvn/intranet/intranet;
    }

location /media/ {
        root /home/hvn/intranet/intranet;
    }

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



    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/xxx.xx/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/xxx.xx/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}
server {
    if ($host = www.xxxx.xx) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = xxx.xx) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    server_name xxx.net *.xxx.xx;
    return 404; # managed by Certbot

What am I doing wrong? Please help me. Thnx in advanced.

Solved it: Had to set in the nginx.conf that nginx runs on the same user that is serving the website:

Check the user in /etc/nginx/nginx.conf Change ownership to user. sudo chown -R nginx:nginx /var/lib/nginx

Back to Top