![](/img/trans.png)
[英]Django on Nginx serving static files but not media files when debug is False
[英]Django stops serving static files when DEBUG is False
我将Docker Compose与此Dockerfile一起使用,该Dockerfile将静态文件夹复制到/ static:
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install --upgrade pip && pip install -r requirements.txt
COPY static /static/
COPY . /code/
在我的设置文件中,我使用:
if env == "dev":
DEBUG = True
else:
DEBUG = False
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = "DENY"
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static/"),
'/static'
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
静态文件在dev中工作,但是当我将env更改为prod时,我开始收到404错误。
那么您看到问题了吗?
注意:此答案也是正确的,但我也接受了上述答案(因为我的应用程序的访问量非常低。)
感谢您的意见。 它们很有用。
这是我的新docker compose文件:
version: '3.5'
services:
nginx:
image: nginx:latest
ports:
- "8002:8000"
volumes:
- $PWD:/code
- ./config/nginx:/etc/nginx/conf.d
- ./static:/static
depends_on:
- web
networks:
- my_net
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
env_file: .env
volumes:
- $PWD:/code
- ./static:/static
expose:
- "8000"
networks:
- my_net
networks:
my_net:
driver: bridge
这是Nginx conf文件:
upstream web {
ip_hash;
server web:8000;
}
server {
location /static/ {
autoindex on;
alias /static/;
}
location / {
proxy_pass http://web/;
}
listen 8000;
server_name localhost;
}
您还应该将“ web”添加到允许的主机:
ALLOWED_HOSTS = ['0.0.0.0', 'localhost', 'web']
更新:settings.py文件:
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
# '/static'
]
STATIC_ROOT = '/static' #os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
就像@dirkgroten所说的那样,您可以在服务的静态文件中设置有效期标头。
另一个解决方案是使用Whitenoise( 感谢Daniel Roseman )。
虽然强烈建议不要在生产中提供Django的静态文件(出于非常充分的理由),但无论如何我还是经常需要这样做。
在某些情况下,它是完全可以接受的(低流量,仅REST API的服务器等)。 如果您需要这样做,此代码段应该可以帮到您。 调整re_path
或使用url()
如果这就是您的django风格)。
from django.contrib.staticfiles.views import serve as serve_static
def _static_butler(request, path, **kwargs):
"""
Serve static files using the django static files configuration
WITHOUT collectstatic. This is slower, but very useful for API
only servers where the static files are really just for /admin
Passing insecure=True allows serve_static to process, and ignores
the DEBUG=False setting
"""
return serve_static(request, path, insecure=True, **kwargs)
urlpatterns = [
...,
re_path(r'static/(.+)', _static_butler)
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.