Python – You don’t have permission to access /index.py on this server

.htaccessapache-2.2cgipython

I am setting up a simple test page in Python. I only have two files: .htaccess and index.py. (Permissions for both set to 755) I get a 403 Forbidden error when trying to view the page – how can I fix this?

.htaccess:

RewriteEngine On
AddHandler application/x-httpd-cgi .py
DirectoryIndex index.py

index.py:

#!/usr/bin/python
print "Content-type: text/html\n\n"
print "test"

Best Answer

Have you checked your error log? It's the first place to look.

I think your AddHandler is incorrect. The documentation says it is used like so:

Syntax: AddHandler handler-name extension [extension] ...

application/x-httpd-cgi isn't a handler, it's a MIME type.

You probably need ExecCGI on (see the docs). This is usually enabled for /cgi-bin/ but if your file's not in there you'll need something like this in your .htaccess

Options +ExecCGI
AddHandler cgi-script .py

This relies on your server allowing .htaccess files. See the AllowOverride documentation.

You don't need RewriteEngine On and DirectoryIndex just sets the file returned when you hit the containing directory (i.e., /python/) with no filename.

This solution just enables execution of .py scripts using mod_cgi. Other solutions which have suggested mod_python will also work but this is more complex and embeds a Python interpreter in the Apache processes. This isn't needed for straight execution using the system Python interpreter.