Convert directories into variables and values in a URL

I recently worked on a project where we dynamically displayed page content with a single PHP script. But we didn’t want to display the PHP script name, variables and their values in the URL.

The script URL schema looked like:

http://website.com/index.php?page=myPage

I wanted to rewrite the URL so that the script, variable and value were displayed as if they were directories, in this form:

http://website.com/myPage
– and –
http://website.com/myPage/
I wanted both URL forms to work the same, because it would be strange to get one kind of content at one and another at the other.

We used Apache rewrite to accomplish this task.

Here’s the content of the .htaccess file in the website’s root directory:

Options +FollowSymLinks
RewriteEngine On
DirectorySlash Off
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f

<IfModule mod_rewrite.c>
 RewriteRule ^([a-z0-9]+)/?$ index.php?page=$1 [NC,L,QSA]
</IfModule>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.