Django + Nginx + Gunicorn-找不到静态文件

Django + Nginx + Gunicorn-找不到静态文件

我在 Ubuntu 22.04.4 服务器上使用 Django+Gunicorn+Nginx 来开发我的 Web 应用程序。我遵循本指南直到最后,我的网站仍在生产中运行。但是,静态文件不起作用(css、图像和 js),我觉得我已经尝试了一切。

仅当我在本地主机上运行激活了 Debug 的 django 开发服务器时,我的静态文件才有效。

我的项目位于 /home/user/visor/prod/visor_scs/。我的静态文件位于 /var/www/myweb.com/static/,我也尝试将它们放在 /home/user/visor/prod/visor_scs/static/,但没有结果(在相应地调整我的 nginx 配置后)。

以下是我的设置.py与静态文件相关:

INSTALLED_APPS = [
...,
'django.contrib.staticfiles',
]

STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/myweb.com/static/'

这是我的gunicorn 服务

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=user
Group=www-data
WorkingDirectory=/home/user/visor/prod/visor_scs
ExecStart=/home/user/visor/prod/visor_scs/prod-envisor/bin/gunicorn \
        --access-logfile - \
        --workers 3 \
        --bind unix:/run/gunicorn.sock \
        visor_scs.wsgi:application

[Install]
WantedBy=multi-user.target

这是我的nginx 配置在/var/nginx/sites-available/visor_scs中:

server {
        listen 80;
        server_name myweb.com;
        location = /favicon.ico { access_log off; log_not_found off; }
        location = /static/ {
                root /var/www/myweb.com/static/;


        }

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

我还尝试使用别名而不是根目录,并将静态文件放在我的项目目录中。每次更改后,我都会重新启动 nginx 和 gunicorn 服务并运行 collectstatic。我还向 www-data 用户授予了静态和项目目录的权限和所有权。

我检查了 gunicorn 和 nginx 的日志,除了所有静态文件的 404 之外,没有什么引起我注意的东西。

最后,以下是浏览器开发控制台中的错误:

GET
http://myweb.com/static/visor/styles.css

GET
http://myweb.com/static/visor/leaflet_style.css

GET
http://myweb.com/static/visor/img/logo_vertical_mediano.png
[HTTP/1.1 404 Not Found 105ms]

El recurso de “http://myweb.com/static/visor/styles.css” fue bloqueado debido a una discordancia del tipo MIME (“text/html”) (X-Content-Type-Options: nosniff).
visor
El recurso de “http://myweb.com/static/visor/leaflet_style.css” fue bloqueado debido a una discordancia del tipo MIME (“text/html”) (X-Content-Type-Options: nosniff).
visor
GET
http://myweb.com/static/visor/styles.css

GET
http://myweb.com/static/visor/leaflet_style.css

El recurso de “http://myweb.com/static/visor/styles.css” fue bloqueado debido a una discordancia del tipo MIME (“text/html”) (X-Content-Type-Options: nosniff).
visor
El recurso de “http://myweb.com/static/visor/leaflet_style.css” fue bloqueado debido a una discordancia del tipo MIME (“text/html”) (X-Content-Type-Options: nosniff).
visor
GET
http://myweb.com/static/visor/img/apple-touch-icon.png
[HTTP/1.1 404 Not Found 33ms]

GET
http://myweb.com/static/visor/img/favicon-16x16.png
[HTTP/1.1 404 Not Found 24ms]

我感觉自己正在撞墙,我会提供任何相关信息/日志。如果您已经读到这里,感谢您的阅读。

答案1

我只需要编辑我的 nginx 设置,删除其中的“=”。

  location /static/ {
    root /var/www/myweb.com;
  }

重新启动 Nginx 后,我的静态文件可以正常工作。

相关内容