Apache: Run a Django project using mod_wsgi and .htaccess

To get Django up and running under your Apache configuration, you'll need to install mod_wsgi first. This will let Apache run Python code.

Assuming your files are in the format of:

image

For this example, the "forum" folder is the subdomain (http://forum.example.com) and the "forum_project" should be your Django project folder (containing manage.py, settings.py, etc).

In your subdomain folder, create a file called "dispatch.wsgi". This file will tell Apache what to do with the incoming request. In that file, paste:

import os, sys

sys.path.append("/home/twig/public_html/forum/forum_project");

# This refers to the "settings.py" file in forum_project
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

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

def application(environ, start_response):
"""Simplest possible application object"""
output = "Hello World"
status = '200 OK'
response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]

Now to create a file called ".htaccess", which will funnel all the URLs into dispatch.wsgi.

RewriteEngine On
RewriteBase /
RewriteRule ^(media/.*)$ - [L]
RewriteRule ^(admin_media/.*)$ - [L]
RewriteRule ^(dispatch\.wsgi/.*)$ - [L]
RewriteRule ^(.*)$ slowpoke/dispatch.wsgi/$1 [QSA,PT,L]

Lastly, add a few lines in your domain's vhost file so it knows to use Python and WSGI for requests.

<IfModule mod_wsgi.c>
WSGIScriptAlias / /home/twig/public_html/forum/dispatch.wsgi
WSGIDaemonProcess myapp processes=5 threads=1 display-name=%{GROUP}
WSGIProcessGroup myapp
WSGIApplicationGroup %{GLOBAL}
</IfModule>

Time to test the server. Open up the browser and point it to your domain. It should display "Hello world". If not, check your error logs. A useful guide to debugging WSGI errors is available on the mod_wsgi documentation pages.

Once its up and running, uncomment the Django wsgi code and delete the application() function from dispatch.wsgi. Your code should now look like this.

import os, sys

sys.path.append("/home/twig/public_html/forum/forum_project");

# This refers to the "settings.py" file in forum_project
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

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

That should be enough to get your project up and running with Apache, Django and mod_wsgi.

See here to serve CSS/JS/image files out of Django. For anything else Django related see here.

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog