Setting up Django with mod_wsgi and Apache

By | September 11, 2009

Configuring Django to use Apache and mod_wsgi

To install apache look at this post

Step 1, download and install the latest version of mod_wsgi

Wget http://modwsgi.googlecode.com/files/mod_wsgi-2.5.tar.gz

Always try to get the latest version from here

Tar –xzvf  mod_wsgi-2.5.tar.gz
cd mod_wsgi-2.5.tar.gz
./configure –with-apxs=/path/to/apache/bin/apxs

(If you do not know the path to your apache then

Updatedb
locate apxs

/path/to/apache/bin/apxs
/path/to/apache/man/man8/apxs.8
/path/to/apache/manual/programs/apxs.html

Select the path to the apxs executable, usually it is in the bin folder as above, and edit the configure command above)

Then type in

Make
make install

Mod_wsgi is now installed,

Firstly, we must create a wsgi file in the django folder,
where your settings .py is located.
Example we call this file mysitewsfile.wsgi

In both the sys.path edit the location to your site,
and the location to the django folder where your settings.py are placed.

We are assuming that the /var/www/mysite1 folder contains all your media and assets folders,
assets folder usually contains images css etc, to be served by apache rather then django, and also the django folder (Which contains the framework and your settings.py)

import os, sys
sys.path.append(‘/var/www/mysite1/’)
sys.path.append(‘/var/www/mysite1/djangofolder/’)
os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘djangofolder.settings’
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

 Now we add a module and the virtualhost to the apache httpd.conf, please make the necessary changes to path’s where needed.

At the top of the httpd.conf you should find a bunch of lines similar to this
LoadModule wsgi_module    modules/mod_wsgi.so
add the above to the httpd.conf so that apache uses the newly installed mod_wsgi

Now we must create the virtual host, add this to the bottom of the httpd.conf

<VirtualHost *>

ServerAdmin youremail@domain.com
Servername mysite.com
Serveralias www.mysite.com
Serveralias mysite.com
DocumentRoot /var/www/mysite1

Alias /media /var/www/mysite1/media/
Alias /assets /var/www/mysite1/assets/

WSGIDaemonProcess mysite1 processes=2 maximum-requests=500 threads=1
WSGIProcessGroup mysite1
WSGIScriptAlias / /var/www/mysite1/djangofolder/mysitewsfile.wsgi

  </VirtualHost>

 Note WSGISCRIPTALIAS points to the file we created before, make sure you point this to the correct location.

to troubleshoot any issues tail –f path/to/your/apache/logs/error_log

 You Should now have a working django application served from apache.

One thought on “Setting up Django with mod_wsgi and Apache

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.