So I just started working with Apache’s mod_rewrite module and I’ve run into a problem I can’t seem to figure out. What I want is to have the address bar display clean URLs either when a user manually types in the URL or when the page is linked to. Right now I get clean URLs when they’re typed in but the query string still shows up in the address bar when the page is linked to. For example:
Typing in, myDomain.com/first takes me the page at myDomain.com/index.php?url=first and displays myDomain.com/first in the address bar.
But, when clicking a link like href=”index.php?url=first”. The address bar displays myDomain.com/index.php?url=first when I want it to display myDomain.com/first.
Here is my .htaccess file located in the same folder as my index file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_\-]+)/?$ index.php?url=$1 [NC,L]
</IfModule>
Here is my index file:
<?php
define('ROOT_DIR', dirname(__FILE__) . '/'); // Define the root directory for use in includes
require_once (ROOT_DIR . 'library/bootstrap.php');
$url = strtolower($_GET['url']);
include(ROOT_DIR . 'views/headerView.php');
switch($url)
{
case "first": include(ROOT_DIR . 'views/firstPageView.php');
break;
case "second": include(ROOT_DIR . 'views/secondPageView.php');
break;
default: include(ROOT_DIR . 'views/homeView.php');
}
include 'views/footerView.php';
?>
And here is homeView.php:
<p>This is the home page.</p>
<p>To the first page. <a href="index.php?url=first">First Page</a></p>
<p>To the second page. <a href="index.php?url=second">Second Page</a></p>
Any advice or help on my linking problem would be greatly appreciated, thank you in advance.
You’ll have to link to the “clean” URL. Remember, you’re not redirecting here. You’re rewriting! That mean’s you’ll have to change this:
To something like this: