本文主要介绍服务器部署时Django需要的配置和uwsgi以及nginx的配置,不介绍Python的安装以及虚拟环境的安装创建,也不涉及Mysql数据库的安装以及配置,Python以及虚拟环境和Mysql的安装可以自行网上搜索,一般不会有坑,能顺利安装配置成功。
1. 上传本地项目到服务器
使用Xftp连接服务器,通过Xftp上传本地项目到服务器指定位置,比如我会上传到 home/username文件夹下.
2. 配置Django项目
在项目的setting.py里面,注释掉STATICFILES_DIRS,新增STATIC_ROOT。
# STATICFILES_DIRS = (
# os.path.join(BASE_DIR,'static'),
# )
STATIC_ROOT = os.path.join(BASE_DIR,'static/'
配置url.py文件,在urlpatterns里面新增:
url(r'media/(?P.*)$', serve, {"document_root": MEDIA_ROOT}),
url(r'^static/(?P.*)$', serve, {"document_root": STATIC_ROOT}),
因为用到了serve、MEDIA_ROOT和STATIC_ROOT,需要导入:
from django.views.static import serve
from newblog.settings import MEDIA_ROOT, STATIC_ROOT
3. 收集静态文件
进入到项目根目录,运行
python manage.py collectstatic
pip install uwsgi
5. 安装nginx
pip install uwsgiyum install nginx
新建nginx.cong文件,输入如下:
user root;
events{}
http{
include /etc/nginx/mime.types;
server{
listen 80;
server_name 你的域名;
index index.html ;
root 你的项目目录;
location /static {
alias 你的项目目录/static; # your Django project's static files - amend as required
}
location /media {
alias 你的项目目录/media;
}
# Finally, send all non-media requests to the Django server.
location / {
include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
uwsgi_pass 127.0.0.1:8000;
}
}
}
用新建的nginx.conf文件替换 /etc/nginx/nginx.conf文件,建议在替换之前先备份原始的nginx.conf文件
新建uwsgi.ini文件,输入如下内容:
# mysite_uwsgi.ini file
[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = 你的项目目录
# Django's wsgi file
module = 项目名.wsgi
# the virtualenv (full path)
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = 127.0.0.1:8000
# ... with appropriate permissions - may be needed
# chmod-socket = 664
# clear environment on exit
vacuum = true
virtualenv = 虚拟环境路径
uwsgi uwsgi.ini -d conf/uwsgi.log(-d后面为你想存放log的路径)
sudo /usr/sbin/nginx
浏览器里输入你的域名,就可以正常访问你的网站了