Apache .htaccess RewriteRule Examples with PHP for Clean URLs

โ€”

by

in

[adinserter block=”34″]

Our code for today will make your website URLs clean and attractive. Clean URLs are user and SEO friendly, it does not contain any query string like:

…page.php?param1=something&id=1111

Thus, giving our users and search engines (like Google) an idea what your link is all about once it was shared to social media or indexed by Google or Bing.

.htaccess rewriterule examples - first example is smashing magazine

We are going to use .htaccess (hypertext access) rewrite rules to achieve these clean URLs. The .htaccess file provide a directory level configuration that is supported by several web servers such as Apache.

Existing or Live Apache .htaccess Rewriterule Examples

Below are other example websites with clean URLs.

Of couse you know this blog, don't you?
Of couse you know this blog, don’t you? :))
Chris' blog
Chris’ blog
Davidโ€™s blog
Davidโ€™s blog

Four Apache .htaccess Rewriterule Examples

Our .htaccess and PHP files are placed in the “htaccess-clean-urls” folder.

.htaccess uses regular expressions to identify which PHP file will be loaded on the browser, based on the parameter(s) given.

We have 4 example codes below. Please note that “localhost” refers to “yoursite.com”. I was using my local server when I did these examples so please keep it in mind.

URL with two parameters: letter and number

This URL:

http://localhost/htaccess-clean-urls/parameter_letter_and_number.php?param=postยถm2=143

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/post/143

.htaccess code used:

RewriteRule ^([a-z]+)\/([0-9]+)\/?$ parameter_letter_and_number.php?param=$1¶m2=$2 [NC]

PHP page used: parameter_letter_and_number.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Clean URL with .htaccess by https://codeofaninja.com/</title>

        </style>
    </head>
<body>

<h1>Parameter: Letter and Number ONLY. This is parameter_letter_and_number.php</h1>
<?php
echo "PARAMETER VALUE 1: " . $_REQUEST['param'];
echo "<br />";
echo "PARAMETER VALUE 2: " . $_REQUEST['param2'];
?>

</body>
</html>

Output screenshot:

.htaccess RewriteRule Example - parameter and number

URL with one parameter: name of the PHP file

This URL:

http://localhost/htaccess-clean-urls/login.php
http://localhost/htaccess-clean-urls/register.php

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/login/
http://localhost/htaccess-clean-urls/register/

.htaccess code used:

RewriteRule ^([a-z]+)\/?$ $1.php [NC]

PHP pages used:

login.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>login - Clean URL tutorial with .htaccess and PHP by https://codeofaninja.com/</title>

        </style>
    </head>
<body>

<h1>Login. This is login.php</h1>

</body>
</html>

register.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>register - Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>

        </style>
    </head>
<body>

<h1>Register. This is register.php</h1>

</body>
</html>

Output Screenshots:

login page clean url
register page rewriterule example

URL with one parameter: numbers

This URL

http://localhost/htaccess-clean-urls/parameter_number.php?param=5254

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/5254/

.htaccess code used:

RewriteRule ^([0-9]+)\/?$ parameter_number.php?param=$1 [NC]

PHP page used: parameter_number.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>parameter is number - Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>

        </style>
    </head>
<body>

<h1>Parameter: Number ONLY. This is parameter_number.php</h1>
<?php echo "PARAMETER VALUE: " . $_REQUEST['param']; ?>

</body>
</html>

Output Screenshot:

htaccess rewriterule number example

URL with one parameter: numbers with underscore

This URL:

http://localhost/htaccess-clean-urls/parameter_number_and_underscore.php?param=143_5254

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/143_5254/

.htaccess code used:

RewriteRule ^([0-9_]+)\/?$ parameter_number_and_underscore.php?param=$1 [NC]

PHP page used: parameter_number_and_underscore.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>parameter is number and underscore- Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>

        </style>
    </head>
<body>

<h1>Parameter: Number and Underscore ONLY. This is parameter_number_and_underscore.php</h1>
<?php echo "PARAMETER VALUE: " . $_REQUEST['param']; ?>

</body>
</html>

Output Screenshot:

htaccess rewriterule example - number and underscore

Complete .htaccess Code Used

The following codes are the ones we used in the examples above, put into one .htaccess file.

<IfModule mod_rewrite.c>

    RewriteEngine on

    RewriteRule ^([a-z]+)\/([0-9]+)\/?$ parameter_letter_and_number.php?param=$1¶m2=$2 [NC]

    RewriteRule ^([a-z]+)\/?$ $1.php [NC]

    RewriteRule ^([0-9]+)\/?$ parameter_number.php?param=$1 [NC]

    RewriteRule ^([0-9_]+)\/?$ parameter_number_and_underscore.php?param=$1 [NC]

</IfModule>

.htaccess RewriteRule Resources

If you want to learn more, here’s a mod_rewrite or regex cheat sheet.
An In Depth Guide to mod_rewrite for Apache
Apache mod_rewrite

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

[purchase_link id=”12376″ text=”Download Now” style=”button” color=”green”]

If you have some questions or want to add more Apache .htaccess RewriteRule examples, please drop it in the comments section below! I will update this post once you did, thanks for your contribution!


Comments

31 responses to “Apache .htaccess RewriteRule Examples with PHP for Clean URLs”

  1. Bob Weston Avatar
    Bob Weston

    Remember, though: Avoid using .htaccess if at all possible.

    1. Hi @disqus_svjnM7VR1k, can you tell us why?

      1. Bob Weston Avatar
        Bob Weston

        https://httpd.apache.org/docs/trunk/howto/htaccess.html#when (straight from the horse’s mouth) sums it up pretty well. http://wiki.nginx.org/LikeApache-htaccess covers some of it too, from a less charitable point of view. Essentially .htaccess files are…pretty much categorically inferior to doing the same thing in the main configuration files unless you are using a shared hosting account or are in a situation where similar restrictions on access need to be applied.

        It may be less of an impact with some of the other servers that support .htaccess; I’m not sure. I actually didn’t realize until I went and looked it up before posting this reply that there were servers besides Apache that supported it.

        I do apologize for posting the original comment without supporting arguments. I must have been sleepy or distracted or something.

        1. thanks

          1. Thanks for adding those references Bob, thanks for visiting @gaassis!

  2. Arvin Kent Avatar
    Arvin Kent

    Sir. How to make the rules work on files on subfolders?

    1. Hi Alvin, how about adding a new .htaccess file to your sub folder?

      1. Arvin Kent Avatar
        Arvin Kent

        Sir. Yes I already did that and it worked but what is the rule that can affect also subfolders with only the use of one .htaccess file sir?

        1. Good to know it works for you, regarding using only 1 .htaccess files, I think you have to deal with RewriteBase, see http://stackoverflow.com/questions/704102/how-does-rewritebase-work-in-htaccess

  3. Hitesh Bansi Ramnathkar Avatar
    Hitesh Bansi Ramnathkar

    Hello, Thank you for the great article. I have a few doubts regarding the mod rewrite rules.

    I have 2 URLS with the same number of parameters lets say:

    1) http://www.yourdomain.com/blogs.php?h_id=1&blog_id=6

    and

    2)www.yourdomain.com/page.php?h_id=5&page_id=9

    how do i go about writing an rewrite rule that will rewrite both the url’s.

    1. ninjazhai Avatar
      ninjazhai

      Hello Hitesh Bansi Ramnathkar, on your first URL, the .htaccess code will be:

      RewriteRule ^([0-9]+)/([0-9]+)/?$ blog.php?param=$1&param2=$2 [NC]

      on the second one, it will be:

      RewriteRule ^([0-9]+)/([0-9]+)/?$ page.php?param=$1&param2=$2 [NC]

  4. Robby Agustinus Avatar
    Robby Agustinus

    Sir, How to load iimg/css/js in parameter_letter_and_number.php? Tq

    1. Hello @robbyagustinus, sorry for the late reply, in those cases, you have to specify the complete URL of your image source.

  5. @vijaykmr you’re welcome! I’m glad it helped your website!

  6. Zeeshan Liaqat Avatar
    Zeeshan Liaqat

    hello i am having trouble with my url conversion i am making a custom php script and i want to convert my urls to make them seo friendly . i am working on localhost and i tried above rewrites but it wont work . can you help me to convert my url ?

    here is my url . : http://localhost:81/allusnews/post.php?id=2&posttitle=In%20joint%20interview,%20Bush,%20Clinton%20talk%202016%20politics%20and%20friendship

  7. Zeeshan Liaqat Avatar
    Zeeshan Liaqat

    hello i am having trouble with my url conversion i am making a custom php script and i want to convert my urls to make them seo friendly . i am working on localhost and i tried above rewrites but it wont work . can you help me to convert my url ?

    here is my url . : http://localhost:81/allusnews/post.php?id=2&posttitle=In%20joint%20interview,%20Bush,%20Clinton%20talk%202016%20politics%20and%20friendship

    1. Hello @disqus_5RW8e2ORut, thanks for dropping by! about your question, your URL is kinda hard to understand, would you please reply with the URL format you want to do? That way, I can suggest an .htaccess code for you.

      1. Zeeshan Liaqat Avatar
        Zeeshan Liaqat

        here is my url explaination :
        hmydomain.com/post.php?getvariable=value&getvariable2=value
        i want this url to look like :
        mydomain.com/getvariable2value/

        i want a general code so that i dont need to convert the htaccess for every post :/

        reply as soon as possible . Thanks

        1. What you want to do cannot be done, this is what is possible:

          Your:

          mydomain.com/post.php?getvariable=value&getvariable2=value

          Will be:

          mydomain.com/post/value1/value2

          RewriteRule will be:

          RewriteRule ^post/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ post.php?getvariable=$1&getvariable2=$2

  8. Abdelmalek NA Avatar
    Abdelmalek NA

    hello thanks for this tuto, but how rewrite url : (delete_record.php?id=xx&param=yyy&…) —> delete.html
    thank you for your help ..

  9. Abdelmalek NA Avatar
    Abdelmalek NA

    sorry for the photo

    1. No worries, I like it @abdelmalekna ! ๐Ÿ˜€

  10. budi liauw Avatar
    budi liauw

    Thanks this helpul for newbeginer like me Lol..

    1. You’re welcome @budiliauw , thanks for the good feedback! Please share our site to one of your friends if you have time. ๐Ÿ™‚

  11. HITESHI TRIVEDI Avatar
    HITESHI TRIVEDI

    i want to redirect to index.php?1 while requesting for Request index.php
    what should i do?

  12. Hi @iamzeeshan , I think it is better to rename your images. Or change the name of your images during upload.

  13. Hi @keithholard, you can try the following rule for that.

    RewriteRule ^([0-9]+)/?$ item.php?param=$1 [NC]

    Make sure .htaccess is inside your ‘xb_master’ directory.

  14. Hayder Kaz Avatar
    Hayder Kaz

    I have to say It has been the best tutorial, I have come across. I am speechless. It made me learn the whole thing in less then 5 minutes.

    1. Hi @Hayder Kaz, thanks for the kind words! Please share this tutorial to your friends and subscribe if you have the time https://www.codeofaninja.com/subscribe

  15. You’re welcome @sudhir600!

  16. Hi @bilawal_gul , you can try this:

    RewriteRule ^([a-z-]+)/?$ $1.php [NC]

Leave a Reply

Your email address will not be published. Required fields are marked *