What we'll do with mod_rewrite is to silently redirect users from page/software/
toindex.php?page=software
etc.
The following is what needs to go into your .htaccess file to accomplish that:
RewriteEngine on
RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]
Let's walk through that RewriteRule, and work out exactly what's going on:
- ^page/
Sees whether the requested page starts with
page/
. If it doesn't, this rule will be ignored.- ([^/.]+)
Here, the enclosing brackets signify that anything that is matched will be remembered by the RewriteRule. Inside the brackets, it says "I'd like one or more characters that aren't a forward slash or a period, please". Whatever is found here will be captured and remembered.
- /?$
Makes sure that the only thing that is found after what was just matched is a possible forward slash, and nothing else. If anything else is found, then this RewriteRule will be ignored.
- index.php?page=$1
The actual page which will be loaded by Apache.
$1
is magically replaced with the text which was captured previously.- [L]
Tells Apache to not process any more RewriteRules if this one was successful.
Let's write a quick page to test that this is working. The following test script will simply echo the name of the page you asked for to the screen, so that you can check that the RewriteRule is working.
<html>
<head>
<title>
Second mod_rewrite example</title> </head> <body> <p> The requested page was: <?php echo $_GET['page']; ?> </p> </body> </html>
Again, upload both the index.php page, and the .htaccess file to the same directory. Then, test it! If you put the page inhttp://www.somesite.com/mime_test/
, then try requestinghttp://www.somesite.com/mime_test/page/software
. The URL in your browser window will show the name of the page which you requested, but the content of the page will be created by the index.php
script! This technique can obviously be extended to pass multiple query strings to a page - all you're limited by is your imagination.
No comments:
Post a Comment