Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs apache apache

Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs


You have to return a single newline, not 'NULL'.

Apache waits for a newline to know when the URL to be rewrite to ends. If your script sends no newline, Apache waits forever.

So just change return ('NULL') to return ('NULL\n'), this will then redirect to /. If you don't want this to happen, have the program to return the URL you want when there's no match in the map.

If you want not to redirect when there's no match I would:

RewriteEngine onRewriteCond %{REQUEST_FILENAME} !-fRewriteCond (${remap:$1}) !NULLRewriteRule (.*_.*) /%1 [R=301]

Use a match in the RewriteCond (this would work with NULL as well, of course). But given your problem, this looks like the proper solution.


The best solution I've come up with thus far is to have the RewriteMap script return the new url or '__NULL__\n' if no redirect is desired and store this value in a ENV variable. Then, check the ENV variable for !__NULL__ and redirect. See .htaccess file below.

Also, if anyone is planning on doing something similar to this, inside of the Python script I wrapped a fair amount of it in try/except blocks to prevent the script from dying (in my case, due to failed file/database reads) and subsequent queries being ignored.

/var/www/webroot/.htaccess

RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.+)$ - [E=REMAP_RESULT:${remap:$1},NS]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{ENV:REMAP_RESULT} !^__NULL__$RewriteRule ^(.+)$ /%{ENV:REMAP_RESULT} [R=301,L]

/var/www/remap.py

#!/usr/bin/pythonimport sysdef getRedirect(str):  try:  # to prevent the script from dying on any errors    new_url = str    # if url needs to be redirected, put this value in new_url    # otherwise new_url remains None    if new_url == str: new_url = '__NULL__'    return new_url  except:    return '__NULL__'while True:  request = sys.stdin.readline().strip()  response = getRedirect(request)  sys.stdout.write(response + '\n')  sys.stdout.flush()

Vinko, you definitely helped me figure this one out. If I had more experience with stackoverflow, you would have received ^ from me. Thank you.

I hope this post helps someone dealing with a similar problem in the future.

Cheers,Andrew