我一直在努力在生产中部署Django的静态文件一整天,但到现在为止我没有运气,所以我绝对需要社区的帮助!
我的nginx配置是:
worker_processes 1;
user nobody nogroup;
pid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;
events {
worker_connections 1024;
accept_mutex off;
}
http {
include mime.types;
default_type application/octet-stream;
access_log /tmp/nginx.access.log combined;
sendfile on;
upstream app_server {
server unix:/tmp/gunicorn.sock fail_timeout=0;
# For a TCP configuration:
# server 192.168.0.7:8000 fail_timeout=0;
}
server {
listen 80 default;
client_max_body_size 4G;
server_name _;
keepalive_timeout 5;
# path for static files
root /home/ubuntu/src/static;
location / {
# checks for static file, if not found proxy to app
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://app_server;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /home/ubuntu/src/static;
}
}
}
在我的django settings.py文件中,我设置了以下内容:
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
当然,我已经运行了collectstatic
django命令,路径/home/ubuntu/src/static
中的文件夹中包含所有相应的文件。
我的部署仍然没有服务任何静态文件:/
有人知道我的设置可能出现什么问题吗?
提前谢谢
答案 0 :(得分:0)
我为我的设置使用了很棒的教程here。希望这可以提供帮助。我可以看到一个明显的变化是将location /static/
用于静态文件,只将location /
直接转发给gunicorn(或者我的情况下是uwsgi)
答案 1 :(得分:0)
将静态别名添加到服务器conf
location /static {
alias /home/ubuntu/src/static; # your Django project's static files - amend as required
}
完整配置应该像
server {
listen 80 default;
client_max_body_size 4G;
server_name _;
keepalive_timeout 5;
# path for static files
# root /home/ubuntu/src/static;
location /static {
alias /home/ubuntu/src/static; # your Django project's static files - amend as required
}
location / {
# checks for static file, if not found proxy to app
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://app_server;
}
error_page 500 502 503 504 /500.html;
location = /500.html {
root /home/ubuntu/src/static;
}
}
}