Django Nginx 静态文件 404
这是我的设置:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = '/home/django-projects/tshirtnation/staticfiles'
这是我的nginx配置:
server {
server_name 77.241.197.95;
access_log off;
location /static/ {
alias /home/django-projects/tshirtnation/staticfiles/;
}
location / {
proxy_pass http://127.0.0.1:8001;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
我已经运行了 python manage.py collectstatic
,这条命令把所有静态文件都复制过来了。我用命令 gunicorn_django --bind:my-ip:8001 启动了服务器,其他功能都正常,就是静态文件有点问题。
编辑:
我运行了
sudo tail /var/log/nginx/error.log
看起来没有静态文件找不到的错误 :/
13 个回答
0
你的问题是,location /
这个设置总是被使用,即使在 location /static/
之后,所以所有的请求都会被转发。
解决这个问题的方法是使用一些 try_files
的技巧。
server {
server_name 77.241.197.95;
access_log off;
location / {
try_files $uri @django;
}
location /static/ {
alias /home/django-projects/tshirtnation/staticfiles/;
try_files $uri =404;
# here we use =404 because there is no need to pass it to gunicorn.
}
location @djago {
proxy_pass http://127.0.0.1:8001;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
1
settings.py:
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
STATIC_ROOT = '/home/calosh/PycharmProjects/Proyecto_AES/static/'
MEDIA_ROOT = '/home/calosh/PycharmProjects/Proyecto_AES/media/'
MEDIA_URL = '/media/'
在nginx的配置文件中(/etc/nginx/sites-enabled/default)
server {
server_name localhost;
access_log off;
location /static/ {
alias /home/calosh/PycharmProjects/Proyecto_AES/static/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}
然后重启nginx服务器:
sudo service nginx restart
接着运行gunicorn:
gunicorn PFT.wsgi
这样就可以在本地电脑或者整个本地网络上提供应用服务(使用80端口)。
http://127.0.0.1/
1
在你的settings.py文件里,加入这一段:
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder'
)
STATIC_ROOT = "/home/django-projects/tshirtnation/staticfiles/"
STATIC_URL = '/static/'
你不需要这一段:
STATICFILES_DIRS = ...
7
试着在你的静态位置前面加上 ^~
这个前缀修饰符,这样就可以跳过正则表达式的检查了:
location ^~ /static/ {
alias /home/django-projects/tshirtnation/staticfiles/;
}
30
我遇到了同样的问题,后来通过修改nginx的设置解决了。具体来说,我把/static/
后面的那个斜杠/
去掉了。
location /static { # "/static" NOT "/static/"
# ...
}