【发布时间】:2021-12-30 18:23:44
【问题描述】:
一切看起来应该可以工作,但我在控制台中收到所有静态文件(包括 css、js 和图像)的 404 错误。我究竟做错了什么?其他一切似乎都很好。
nginx.conf
server {
listen 443 ssl;
server_name www.${NGINX_HOST};
ssl_certificate /etc/letsencrypt/live/${NGINX_HOST}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${NGINX_HOST}/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/${NGINX_HOST}/chain.pem;
location / {
proxy_pass http://api;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /static {
autoindex on;
alias /myapp/collectedstatic/;
}
location /media/ {
autoindex on;
alias /myapp/media/;
}
}
settings.py
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
...
MIDDLEWARE = [
...
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'collectedstatic')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
【问题讨论】:
-
location /块必须位于更具体的位置之后。 Nginx 依次遍历位置,location /匹配所有内容,跳过location /static和location /media -
/static 在位置但 /static/ 在 STATIC_URL 中。