How to emulate mod_rewrite in PHP
- by Tyler Crompton
I have a few URLs that I want to map to certain files via PHP. Currently, I am just using mod_rewrite in Apache. However, my application is getting too large for the rewriting to be done with regular expressions. So I created a file router.php that does the rewriting. I understand to do a redirect I could just send the Location: header. However, I don't always want to do a redirect. For example, I may want /api/item/ to map to the file /herp/derp.php relative to the document root. I need to preserve the HTTP method as well. "No problem," I thought. I made my .htaccess have the following snippet.
RewriteEngine On
RewriteRule ^api/item/$ /cgi-bin/router.php [L]
And my router.php file looks as follows:
<?php
$uri = parse_url($_SERVER['REQUEST_URI']);
$query = isset($uri['query']) ? $uri['query'] ? array();
// some code that modifies the query
require_once "{$_SERVER['DOCUMENT_ROOT']}/herp/derp.php?" . http_build_query($query);
?>
However, this doesn't work, because the OS is looking for a file named derp.php?some=query. How can I simulate a rewrite rule such as RewriteRule ^api/item/$ /herp/derp/ [L] in PHP. In other words, how do I tell the server to process a different URL than requested and preserve the query and HTTP method without causing a redirect?
Note: Using variables set in router.php is less than desirable and is bad structure since it's only supposed to be responsible for handling URLs. I am open to using a light-weight third party solution.