Redirecting HTTP requests to a Python script in Apache2
authored by Frank Lynam at 05/02/2013 19:42:29
This blog post shows how to configure your Apache2 service to accept requests for a virtual directory, which will then be redirected on to a Python script. Obviously, you could adapt these instructions quite easily to redirect to a PHP or any other script or indeed to redirect to a static file.
My setup is as follows:
· Ubuntu v12.04.1 LTS
· Apache 2.2.22
· Python 2.7.3
· Web Server Gateway Interface (WGSI) 3.3-4
First off, you need to setup your WSGI Apache2 module. Install it using apt-get install and then go to the /etc/apache2/mods-enabled directory. Open up the wsgi.conf file and replace any content with the following lines:
# Handle all .py files with mod_wsgi
# Deny access to compiled binaries
# You should not serve these to anyone
Deny from all
This instructs Apache2 to first route all served files that have a .py extension to the WSGI compiler before sending it on to the user.
Next, you need to setup your virtual directory. On my Apache2 setup I’m using virtual hosts and so I do this in the /etc/apache2/sites-enabled/000-default file (or whichever file that represents the site that you want to affect). Add in the following lines at the top of the relevant virtual host’s tag:
RewriteEngine On RewriteOptions Inherit
RewriteRule ^/rdf(.*)$ /var/www/python/main.py?$1
This instructs Apache2 to redirect all requests that are received for [site_root]/rdf/ to the script located /var/www/python/main.py. Any additional characters contained in the requested URL will be sent on to the Python script as a query string. These can then be accessed within the script via environment['QUERY_STRING'].
For example if the user sends a request for [site_root]/rdf/test the Python script’s environment['QUERY_STRING'] will contain the string ‘test’.
Good doc. A few questions:
- Is the first <filesmatch> missing a .py regular expression? How does it know to match the .py files?
- Should 'RewriteEngine On RewriteOptions Inherit' be on separate lines? RewriteOptions is probably not required inside a VirtualHost block.
- The RewriteRule at the moment takes rdf followed by anything. For example, it matches rdfsomething. You probably want it to only match rdf/something. You could try two rules where the second one requires a /, like this:
RewriteRule ^/rdf$ /var/www/python/main.py
RewriteRule ^/rdf/(.*)$ /var/www/python/main.py?$1
(henry, 07/02/2013 12:00:10)
Thanks for the comments.
Yep, the regular expression is missing in the FileMatch tag. It must have been removed when I copied it over - a problem with '<' characters in HTML, I think.
I'll try omitting the RewriteOptions command and will put in that '/' suggestion.
(Frank Lynam, 07/02/2013 12:14:19)