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
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.www.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’.

Rick Donato

Want to become a Django expert?

Here is our hand-picked selection of the best courses you can find online:
The Complete Web Development Bootcamp course
Django Practical Guide course
Django Full Stack Developer Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial