简体   繁体   English

使用Nginx + Gunicorn + Django提供静态文件

[英]Serving static files with Nginx + Gunicorn + Django

This is my nginx config: 这是我的nginx配置:

    server {
        listen 80;
        server_name localhost;

        keepalive_timeout 5;

        access_log /home/tunde/django-projects/mumu/nginx/access.log;
        error_log /home/tunde/django-projects/mumu/nginx/error.log;

        root /home/tunde/django-projects/mumu;

        location / {
            try_files $uri @proxy_to_app;
        }

        location @proxy_to_app {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://127.0.0.1:8000;
        }
    }

My settings.py looks like: 我的settings.py看起来像:

    import os
    settings_dir = os.path.dirname(__file__)
    PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))

    STATIC_ROOT = '/home/tunde/django-projects/mumu/STATIC/'
    STATIC_URL = '/static/'

    STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static/'),
    )

My supervisord.conf file looks like: 我的supervisord.conf文件如下所示:

[program: mumu]
command = /home/tunde/ENV1/bin/gunicorn -w 1 --bind=127.0.0.1:8000 mumu.wsgi:application
directory = /home/tunde/django-projects/mumu/
stdout_logfile= /home/tunde/django-projects/mumu/supervisor/logfile.log
stderr_logfile= /home/tunde/django-projects/mumu/supervisor/error.log
user = tunde

The problem is that static files don't get served and I have no idea what I'm doing wrong. 问题是静态文件没有得到服务,我不知道我做错了什么。 A url like /static/css/styles.css returns a 404. Help will be greatly appreciated. 像/static/css/styles.css这样的网址会返回404.非常感谢帮助。

You need to create an nginx location block that matches the location of your django STATIC_URL . 您需要创建一个与您的django STATIC_URL的位置匹配的nginx位置块。 As you have it configured, nginx is also forwarding requests for static assets to your django application. 正如您配置的那样,nginx还会将对静态资产的请求转发到您的django应用程序。 I'm guessing you are seeing the 404 errors in your django application log? 我猜你在django应用程序日志中看到了404错误? You want nginx to handle these requests, not django. 您希望nginx处理这些请求,而不是django。

location /static {
    alias /home/tunde/django-projects/mumu/STATIC/; 
}

Be sure to run the django admin command collectstatic to make sure all the static assets get copied to the STATIC_ROOT directory. 确保运行django admin命令 collectstatic以确保将所有静态资产复制到STATIC_ROOT目录。

location / {
    try_files $uri @proxy_to_app;
}

Please change $uri -> $request_uri 请更改$uri -> $request_uri

location / {
    try_files $request_uri @proxy_to_app;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM