Apache and mod_wsgi on Ubuntu 14.04 (Trusty Tahr)

Select distribution:
Traducciones al Español
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Deprecated

This guide has been deprecated and is no longer being maintained.

The WSGI specification provides a standard and efficient method for dynamic web applications to communicate with web servers. mod_wsgi provides a method for simply deploying WSGI applications with Apache. WSGI is used to deploy applications written with frameworks and tools like Django, Web.py, Werkzug, Chery.py, TurboGears, and Flask. This guides outline this installation and configuration process for WSGI with Apache on Ubuntu 14.04.

Before You Begin

  1. Ensure that you have followed the Getting Started and Securing Your Server guides, and the Linode’s hostname is set .

  2. We recommend that you are already familiar with Apache before beginning this guide.

  3. Update your system:

    sudo apt-get update
    sudo apt-get upgrade
    
Note
The steps required in this guide require root privileges. Be sure to run the steps below as root or with the sudo prefix. For more information on privileges see our Users and Groups guide.

Install Dependencies

Issue the following commands to ensure that your system’s package repositories and installed programs are up to date and that all required software is installed:

apt-get install apache2 python-setuptools libapache2-mod-wsgi

Your application may require additional dependencies. Install these either using the Ubuntu package tools or by using the easy_install command included in python-setuptools before proceeding.

Configure WSGI Handler

In order for mod_wsgi to be able to provide access to your application, you will need to create a application.wsgi file inside of your application directory. The application directory should be located outside of your DocumentRoot. The following three sections each present a different application.wsgi example file to illustrate the basic structure of this file:

Basic Hello World WSGI Configuration

In this example, the application is stored in /var/www/html/example.com/application directory. Modify this example and all following examples to conform to the actual files and locations used in your deployment.

File: /var/www/html/example.com/application/application.wsgi
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import os
import sys

sys.path.append('/var/www/html/example.com/application')

os.environ['PYTHON_EGG_CACHE'] = '/var/www/html/example.com/.python-egg'

def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

You must append the path of your application to the system path as above. The declaration of the PYTHON_EGG_CACHE variable is optional but may be required for some applications when WSGI scripts are executed with the permissions of the web server. The WSGI application must be callable as application, regardless of how the application code is structured.

Web.py WSGI Configuration

In this example the Web.py application is embedded in a application.wsgi file. The Web.py Framework must be installed in order for the following application to run successfully.

File: /var/www/html/example.com/application/application.wsgi
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import web

urls = (
    '/(.*)', 'hello'
)

class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app.run()

app = web.application(urls, globals(), autoreload=False)
application = app.wsgifunc()

Django WSGI Configuration

The following example application.wsgi file is configured for Django applications:

File: /var/www/html/example.com/application/application.wsgi
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import os
import sys

sys.path.append('/var/www/html/example.com/application')

os.environ['PYTHON_EGG_CACHE'] = '/var/www/html/example.com/.python-egg'

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

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

Django must be installed on your system along with a working Django application before this example will function. The DJANGO_SETTINGS_MODULE points to the “settings.py file for your application, which would be located at /var/www/html/example.com/application/settings.py in the case of this example.

Configure Apache

Deploy the following VirtualHost configuration and modify the paths and domains to reflect the requirements of your application:

File: Apache `VirtualHost` Configuration
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<VirtualHost *:80>
   ServerName example.com
   ServerAlias www.example.com
   ServerAdmin username@example.com

   DocumentRoot /var/www/html/example.com/public_html

   ErrorLog /var/www/html/example.com/logs/error.log
   CustomLog /var/www/html/example.com/logs/access.log combined

   WSGIScriptAlias / /var/www/html/example.com/application/application.wsgi

   Alias /robots.txt /var/www/html/example.com/public_html/robots.txt
   Alias /favicon.ico /var/www/html/example.com/public_html/favicon.ico
   Alias /images /var/www/html/example.com/public_html/images
   Alias /static /var/www/html/example.com/public_html/static
</VirtualHost>

In this example, the WSGIScriptAlias directive tells Apache that for this VirtualHost, all requests below / should be handled by the WSGI script specified. The series of four Alias directives allow Apache to serve the robots.txt and favicon.ico files as well as all resources beneath the /images and /static locations, directly from the DocumentRoot without engaging the WSGI application. You can add as many Alias directives as you require.

When you have configured your Apache VirtualHost, issue the following command to restart the web server:

service apache2 restart

You will need to restart the web server every time the application.wsgi file changes. However, all other modifications to your application do not require a web server restart. Congratulations! You have now successfully deployed a WSGI application using mod_wsgi.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on


Your Feedback Is Important

Let us know if this guide was helpful to you.


Join the conversation.
Read other comments or post your own below. Comments must be respectful, constructive, and relevant to the topic of the guide. Do not post external links or advertisements. Before posting, consider if your comment would be better addressed by contacting our Support team or asking on our Community Site.
The Disqus commenting system for Linode Docs requires the acceptance of Functional Cookies, which allow us to analyze site usage so we can measure and improve performance. To view and create comments for this article, please update your Cookie Preferences on this website and refresh this web page. Please note: You must have JavaScript enabled in your browser.