Reputation: 1801
So I just started messing around with Apache's rewrite module and would like to make sure I have this right because I've seen it done a few different ways. My example code is just an experiment for now but it might end up being the basic structure of a new project I'm working on.
Here is my .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_\-]+)/?$ index.php?id=$1 [L,NC]
</IfModule>
My index file:
<?php
include 'views/headerView.php';
switch(strtolower($_GET['id']))
{
case "first": include 'views/firstPageView.php';
break;
case "second": include 'views/secondPageView.php';
break;
default: include 'views/homeView.php';
}
include 'views/footerView.php';
?>
And the default homeView template:
<p>This is the home page.</p>
<p>To the first page. <a href="first">First Page</a></p>
<p>To the second page. <a href="second">Second Page</a></p>
My main concern is only having the url "first" and "second" in the anchor tags on the template. The urls are used in the switch on the index file to determine which view to show. I'm doing it this way so when the user clicks a link, the word "first" or "second" would be used in the rewrite module's back reference and would show up in the url as domain.com/first instead of domain.com/?id=first. So am I on the right track here or am I missing something? Any helpful advice would be appreciated, thank you.
Upvotes: 4
Views: 649
Reputation: 143876
So am I on the right track here or am I missing something? Any helpful advice would be appreciated, thank you.
You are on the right track. There's nothing wrong with what you're doing here. You're going to have to, of course, tweak things but in general you're on the right track. You may want to have something that generates the links for you, some kind of mapping or something. So the "first" and that mapped to "views/firstPageView.php". You can then use that in your index.php to handle the routing as well as it to generate links. So if something like "first" gets changed to "something_else", you won't need to go to all the templates and change them by hand.
Additionally, you have the mod_rewrite rule handle a possible trailing slash. There's a lot of randomness that can pop up because of trailing slashes. Apache will 301 redirect a URL missing the trailing slash to one that includes the trailing slash when mod_dir thinks the request is for a directory. You may want to make all your links have a trailing slash to avoid this. Also, if you have a trailing slash, relative links like <a href="first">First Page</a>
may stop working because the URI base is now /first/
instead of /
.
Upvotes: 2