Super simple .htaccess rewrite to create user friendly query URLs

So you want to remove extensions from your PHP files and have glamorous and readable urls that contain queries?

The first step is to create a .htaccess file, which should contain the following code and be saved in the same folder as you intend to save the index.php file

RewriteEngine on

RewriteRule ^([a-zA-Z0-9]+|)/?$ index.php?name=$1 # Handle requests for "index.php"

What does all this stuff mean?

We're turning on the rewrite engine and writing a rewrite rule, then inserting some regex and telling the rewrite engine what to do with the text from the URL string in the index.php?name=$1 part

OK, I kind of get it what's next

Now create the index.php file and insert the following

<?php echo $_GET['name']; ?>

Now it's time to test

You'll need to be running something like MAMP or have this code on your server. Type the first part of the URL so that you are pointing the web browser at the folder that contains the two files you created. Next type after the forward slash a word, e.g.

http://localhost:8888/rewrite/myname

Here my files were saved in a folder called rewrite (and I was using MAMP).

What else can I do?

Let's add what looks like a folder to our string but isn't. We'll call it names.

RewriteEngine on

RewriteRule ^names/([a-zA-Z0-9]+|)/?$ index.php?name=$1 # Handle requests for "index.php"

Now we need to update our URL to read:

http://localhost:8888/rewrite/names/myname

Are there any other things to think about?

In the current code it is very easy for a trailing slash and for anything placed after it to land us at a not found page so we might make this less sensitive with something like this:

RewriteRule ^names/([a-zA-Z0-9]+|)(/|)([a-zA-Z0-9]+|)/?$ index.php?name=$1 # Handle requests for "index.php"

If you want to read the additional text, then the second part of the RewriteRule needs to be amended, e.g.

index.php?name=$1&gender=$3

And an additional GET added to your code, e.g.

<?php echo echo "Name: ".$_GET['name']." <br /> Gender: ".$_GET['gender']; ?>

Is that all you've got for us?

I'm not pretending this is a comprehensive guide, but sometimes you need the basics to make a start, and that's what this is. Thanks for listening.


Comments

  1. This is a very nice article on Htaccess rewrite i like your article.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

Post a Comment