Main Content

Using a MySQL database to control mod_rewrite via PHP

Archive - Originally posted on "The Horse's Mouth" - 2007-10-06 00:08:23 - Graham Ellis

Question: How can I set up Apache httpd / mod_proxy to use a program rather that a list of URL patterns to control my rewrites?

Specify a rewrite map type prg in your httpd.conf or .htaccess file. For example:

RewriteEngine On
RewriteMap tryme prg:/home/trainee/website/andy
RewriteRule (.*\.htm) ${tryme:}


Question: How can I write that program in PHP

1. Start the script with a line such as
#!/usr/local/bin/php
or a pointer to whereever the cli version of PHP is located.

2. Ensure you have a
set_time_limit(0);
at the top of that code to ensure it won't time out

3. Open your STDIN for interactive read within the PHP:
$keyboard = fopen("php://stdin","r");

4. Write a daemonic loop to read from keyboard, translate as appropriate, and printg out the mapped URL.

When you restart you httpd with the newly configured httpd.conf, your mapping should be in place. Well - it works for me ;-) but you do need to watch things like buffering!

Question: Can that program access a MySQL database?

Yes - just add in a mysql_connect or mysqli_connect at the top of your code, and appropriate database queries further down, and that's all there is too it. Remember you may need to "bounce" your web server to restart the rewrite daemon.

Putting all the answers together?

There's source code showing most of this ... a fully working example .. here