Recommended reading

Pretty URLs With .htaccess On Apache

August 7, 2019 by Andreas Wik

If you’re building your site or whatever on Apache, you might find this tip useful. Instead of having ugly URLs like mysite.com/?page=article?id=939982 you can easily turn it into mysite.com/article/393982 with a few lines in your .htaccess file.

Create a file named .htaccess and drop it in your site’s home directory (chances are you already got it there, in that case just update it) and add the following line at the top:


RewriteEngine On

 

Next, we create some rules for how the URLs may look. We need to create a rule for no parameters, one parameter named page and one when both page and id is passed.

First we create a rule for when the page parameter is set. We have two variations of each rule to handle a possible trailing slash. Both mysite.com/about and mysite.com/about/ should work.


RewriteRule ^([a-zA-Z0-9]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9]+)/$ index.php?page=$1

 

Finally, a rule for when both page and ID is set:


RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)$ index.php?page=$1&id=$2
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/$ index.php?page=$1&id=$2

 

The final .htaccess file:


RewriteEngine On

RewriteRule ^([a-zA-Z0-9]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9]+)/$ index.php?page=$1

RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)$ index.php?page=$1&id=$2
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/$ index.php?page=$1&id=$2

 

With this in place, we could do something like this in PHP:


if(isset($_GET['page'])) {

    $page = $_GET['page'];

    if($_GET['page'] == 'user') {

        $username = $_GET['id'];

        // Show profile page for user with username $username
    }
    else if($_GET['page'] == 'article') {

        $article_id = $_GET['id'];

        // Show article with article ID $article_id
    }
}
else {

    // Home page
}

 

Yeah, you get the point! Neat.

Recommended reading

Share this article