fir3net
PPS-Firenetbanner-780.5x190-30-03-17

How do I configure Apache to serve my Django website ?

Summary

In order for Apache to serve your Django website WSGI is configured.

The Web Server Gateway Interface (WSGI) defines a simple and universal interface between web servers and web applications or frameworks for the Python programming language (wikipedia).

Note :

  • The following steps are based on a Linux Centos based distro.
  • The following steps within this article are based on the following Django setup:

[root@Fileserver /]# tree /opt/django/
/opt/django/
|-- yourproject
| | |-- TEMPLATES
| | |-- input.html
| | |-- output.html
| |-- __init__.py
| |-- __init__.pyc
| |-- apache
| | `-- django.wsgi
| |-- manage.py
| |-- yourapp
| | |-- __init__.py
| | |-- __init__.pyc
| | |-- models.py
| | |-- models.pyc
| | |-- tests.py
| | |-- views.py
| | `-- views.pyc
| |-- settings.py
| |-- settings.pyc
| |-- urls.py
| `-- urls.pyc

Compile

First the WSGI module is compiled and installed. This is achieved via the following commands,

yum install httpd-devel
yum install python-devel
cd ~
wget http://modwsgi.googlecode.com/files/mod_wsgi-3.3.tar.gz
tar -xvzf mod_wsgi-3.3.tar.gz
cd mod_wsgi-3.3
./configure
make
make install

Configure Django

Next create a new file within '/<django root>/<project>/apache/django.wsgi'.

cd /opt/django
cd project
mkdir apache ; cd apache

 Within django.wsgi add the following :

import os, sys

path = '/opt/django/yourproject'
if path not in sys.path:
   sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

Configure Apache

Within the Apache configuration file '/etc/httpd/conf/httpd.conf' add the following line,

LoadModule wsgi_module modules/mod_wsgi.so

Next create a new file '/etc/httpd/conf.d/django.conf'. This new file will contain,

#
# Django settings.
#
NameVirtualHost *

<VirtualHost *:80>
  ServerAlias tools.fir3net.com
  WSGIScriptAlias / /opt/django/yourproject/apache/django.wsgi

  <Directory /opt/django/yourproject/apache>
    Order deny,allow
    Allow from all
  </Directory>
</VirtualHost>

Once done restart the Apache daemon by running the command '/etc/init.d/httpd restart'.

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001