Python – Redirect to Python script in .htaccess while maintaining request URL

.htaccessapache-2.2pythonscriptalias

I have a website configured with Apache for http://www.example.com located in /var/www/example.com/. For an arbitrary sub-path of this website I would like to have all requests handled by a Python script. e.g. all requests for http://www.example.com/foo/bar/ and below would be handled by /var/www/example.com/foo/bar/index.py.

One way to accomplish this is to use the ScriptAlias directive in the Apache config/virtual host, but I would like to accomplish this in the .htaccess file if possible as I'd rather not have to modify the Apache config every time I which to create a new directory with a Python script.

I have tried doing this using mod_rewrite as shown below, but this has problems in that the Python script thinks the request URL contains /index.py/ which means that some URLs it generates for redirects are incorrect (this is causes problems such as this question).

RewriteEngine on
RewriteBase /foo/bar/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.py/$1 [L]

Is there another way to accomplish this or will I have to use ScriptAlias?

Best Answer

It doesn't look like this is possible using purely .htaccess and mod_rewrite so it will either have to be done using ScriptAlias or in the script itself.