This is what I do for Seach Engine Friendly URLs with unlimited levels. It also gives you the option to allow query strings or not and will not rewrite URLs for real folders or files such as images, CSS and JavaScript.
Apache ...
# Do not use htaccess if you can avoid it, instead write all of this in the httpd.conf <VirtualHost /> and disable .htaccess for performance/security. RewriteEngine On RewriteBase /
PHP ...
<?php /* Title: Request Gets the client request and sanitizes the user input. Returns: Array of parts of the URL. > $request = /path/to/page/ > var_dump($request); > array(3) { [0]=> string(4) "path" [1]=> string(2) "to" [2]=> string(4) "page" } */ // Check request exists if (isset($_GET['request']) && !empty($_GET['request'])) { // Yes. Sanitize request. // request should be made lowercase, as URLs should not be case-sensitive. $request = strtolower($_GET['request']); // Sanitize request incase the user tries to circumvent the .htaccess rules and uses the query string directly. index.php?request= $request = preg_replace("([^a-z0-9-/])", '', $request); // Check if request ends with trailing slash to ensure all crawled URLs end with a trailing slash. ($request does not include other query strings or anchors) if ((substr($request, -1, 1)) == '/') { // Yes, request should now be safe to use. $safe['url'] = $request; // Split request into an array with values for each directory. $safe['request'] = explode('/', $request, -1); // Destroy user input to prevent usage. unset($_GET['request'], $request); } else { // No, redirect to request with trailing slash. header('Location: /' . $request . '/', true, 301); exit; } } else { // No. $safe['request'] = false; } ?>
Then I have a routing file that processes the request using the appropriate functions. This may seem like a lot of code, but it helps keep everything organized and efficient, as I only include the classes / functions that the request requires.
I am considering releasing a library with code (Urgh, not another frame that I hear), I use for my projects, so feel free to use the code under GPL v3.
Hope this helps.
user201305
source share