Django + Nginx 获取静态内容时出现500错误

Django + Nginx 500 error when fetching static content

我在使用 Django、Nginx 和 Gunicorn 提供静态内容时遇到问题。我可以从我的 /media/ 文件夹以及 html 提供媒体文件(图像),但是对 /static/ 文件夹的静态请求会产生 500 个错误。

I 运行 collectstatic 收集 /opt/myapp/myapp/myapp/static/

中的所有静态

这是我的 Nginx 配置:

server {
    listen 80;
    server_name <ip_address>;

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /static/ {
            alias /opt/myapp/myapp/myapp/static/;
    }

    location = /media/ {
            alias /opt/myapp/myapp/myapp/media/;
    }


    location / {
            include proxy_params;
            proxy_pass http://unix:/opt/myapp/myapp/myapp/myapp.sock;
    }
}

还有 Django urls.py:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('core.urls')),
    url(r'^accounts/', include('allauth.urls')),
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 
   + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Django settings.py:

STATICFILES_DIRS = [
    '/opt/myapp/myapp/myapp/core/static',
]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'static')

以及来自 Nginx access.log 的示例(error.log 中没有错误):

"GET /static/markup/css/index.css HTTP/1.1" 500 63893 "http://104.131.44.215/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"

你的 settings.py 长什么样?

编辑:

  1. 再次查看您的代码。在 Nginx 中你有不同的路径不像 settings.py!
  2. 您可能误解了 Django 文档(staticfiles_dirs 与 static_root)
  3. 你的 STATICFILES_DIRS 应该是这样的

STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )

  1. 如果这不起作用,请更改您的 STATIC_ROOT(必须与 staticfiles_dirs 不同的路径)并且不要忘记 运行 collectstatic