You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux VPS部署Django项目时Nginx静态文件权限问题求助

Django部署:Nginx无法访问静态文件(权限拒绝)

问题现象

Nginx error.log报错:

open() "/home/sam/testdjango/static/admin/js/nav_sidebar.js" failed (13: Permission denied)

相关配置及权限信息

1. nginx.conf核心配置

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {
        sendfile on;
        tcp_nopush on;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers on;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

2. Nginx站点配置(sites-available)

server {
    listen 80;
    server_name 185.8.174.180;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sam/testdjango;
    }

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

3. 目录及进程权限

  • Gunicorn运行用户:sam,组:www-data
  • 项目目录权限:
total 140
-rw-r--r-- 1 sam sam      131072 Apr 25 21:54 db.sqlite3
-rwxrwxr-x 1 sam sam         666 Apr 25 11:11 manage.py
drwxrwxrwx 3 sam www-data   4096 Apr 25 13:16 static
drwxrwxr-x 3 sam sam        4096 Apr 25 21:05 testdjango

解决方案

1. 修复父目录访问权限

Linux下进程需要目录的执行权限才能进入目录。当前static目录权限为777,但Nginx运行用户www-data无法访问默认权限为700的/home/sam目录,导致无法进入static目录。

执行命令修改/home/sam目录权限,让其他用户拥有执行权限:

chmod o+x /home/sam

如需更安全的配置,可将sam用户加入www-data组,再给目录组添加执行权限:

usermod -aG www-data sam
chmod g+x /home/sam

2. 验证并修复静态文件权限

检查目标文件是否允许www-data读取:

ls -l /home/sam/testdjango/static/admin/js/nav_sidebar.js

确保权限包含其他用户可读(如-rw-r--r--),若不符合,执行批量修改命令:

chmod -R o+r /home/sam/testdjango/static/

3. 重启Nginx生效

修改权限后重启Nginx服务:

sudo systemctl restart nginx

内容的提问来源于stack exchange,提问作者Nikolat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 06:27:40