ubuntu16下django+apache配置

来源:互联网 发布:使命召唤olmr23数据 编辑:程序博客网 时间:2024/05/16 09:26

  网上很多教程都是比较老的了,由于框架更新有一些变化,所以配置卡了挺久,本文环境为ubuntu16.04+django1.10.4+apache2.4.18,将来可能随着版本更新配置方法会有变化(比如一些命令的改动)就请参考最新的教程。

一、软件安装

需要安装apache2,django,mod_wsgi,假设你的系统已经安装pip,否则使用

sudo apt-get install python-pip

安装pip,然后开始安装上述框架。

sudo apt-get install apache2sudo apt-get install libapache2-mod-wsgisudo -H pip install django

二、新建django项目

其前往你所希望的目录,使用startproject命令建立新的django项目,如以下命令创建一个叫hello的新网站项目

cd ~/django-admin.py startproject hello

三、编辑apache配置文件

在apache的配置文件目录下新建我们项目hello的配置文件hello.conf,其中servername和serverAlias改成你自己电脑的ip(用ifconfig指令查看),项目路径改成你自己的

sudo vim /etc/apache2/sites-available/hello.conf
#hello.conf<VirtualHost *:8080>    ServerName 172.18.42.170    ServerAlias 172.18.42.170    ServerAdmin ace@gmail.com    <Directory /home/ace/hello>        Require all granted    </Directory>    WSGIScriptAlias / /home/ace/hello/hello/wsgi.py    <Directory /home/ace/hello/hello>    <Files wsgi.py>        Require all granted    </Files>    </Directory></VirtualHost>

四、修改hello项目的wsgi.py文件

删除文件原有的内容,替换成以下内容,其中xxx.setting改成你的项目的对应名字,如项目叫hello则改成hello.setting

 sudo vim ~/hello/hello/wsgi.py
#wsgi.pyimport osPROJECT_DIR = os.path.dirname(os.path.dirname(__file__))import sys sys.path.insert(0,PROJECT_DIR)os.environ["DJANGO_SETTINGS_MODULE"] = "hello.settings" from django.core.wsgi import get_wsgi_applicationapplication = get_wsgi_application()

五、修改端口文件

我们的项目配置成通过8080端口发布出去,所以我们需要监听8080端口,所以我们要修改apache的端口配置文件,在Listen 80那行下面添加一行Listen 8080

sudo vim /etc/apache2/ports.conf
# If you just change the port or add more ports here, you will likely also# have to change the VirtualHost statement in# /etc/apache2/sites-enabled/000-default.confListen 80Listen 8080<IfModule ssl_module>    Listen 443</IfModule><IfModule mod_gnutls.c>    Listen 443</IfModule># vim: syntax=apache ts=4 sw=4 sts=4 sr noet

六、完成配置

使用a2ensite指令把hello项目的配置文件添加进apache框架,然后重启框架和重新载入,如果重启失败可以使用sudo apache2ctl -t检查配置文件语法是否有错。

sudo a2ensite hello.confsudo service apache2 restartsudo service apache2 reload

七、访问网站

这时可以在浏览器通过localhost:8080访问到hello项目的It works.页面了,但是我们服务器需要通过ip地址访问的,这时需要修改hello项目下的setting.py文件,在ALLOWED_HOSTS中加入允许通过哪些ip访问到本网站。

 sudo vim ~/hello/hello/settings.py

我的配置如下:(172.18.42.170为本机ip)

ALLOWED_HOSTS = ['172.18.42.170','localhost']

每次修改完项目后都需要执行reload命令修改才会生效

sudo service apache2 reload

现在除了可以用loadlhost:8080 还可以用172.18.42.170:8080访问到hello项目了。

0 0