Bart Simons

Bart Simons


Thoughts, stories and ideas.

Bart Simons
Author

Share


Tags


Twitter


Pretty URLs in Apache - Getting Started Tutorial

Bart SimonsBart Simons

Ever wanted to create beautiful URLs for your self-hosted websites? This page has got you covered with all just about the information you need to get started. All functionality which is demonstrated on this page is made possible by mod_rewrite, also known as the 'rewrite' module. This module gives system administrators the possibility to rewrite URL paths, as I shall demonstrate:

Let's say Mr. X has a website called mywebsite.corp with a single page called test.php. He currently visits his page like this:

mywebsite.corp before any modification

Mr.X is not happy with how the php file extension is exposed to the user, and wants to make his page URL look better by removing the php extension. The first thing he has to do is to enable the rewrite module which is fairly simple:

a2enmod rewrite
```

Now, all that is left to do is to write the rewrite rule inside a Directory tag in apache.conf like this:

```
<Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
        RewriteEngine On
        RewriteRule ^test$ /test.php
</Directory>
```

Restart your web server with `service apache2 restart` and let's see if things work the way we want:

![mywebsite.corp after modification](/content/images/2017/07/Screen-Shot-2017-07-10-at-16.30.59.png)

It works! Now, let's dive deeper into what the RewriteRule line does

^ is the character to indicate the root URL of your website
$ is the character to indicate the end of the URL to match


This has been a simple demonstration of what you can do and accomplish with mod_rewrite. However, you can do so much more with this module. Let's take a look at regular expressions and how to use with rewrite rules:

![mywebsite.corp before second modification](/content/images/2017/07/Screen-Shot-2017-07-10-at-17.36.09.png)

With this directory block:

<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
RewriteEngine On
RewriteRule ^users/(\d+)$ /users.php?id=$1


We are able to create an URL rewrite that functions like this:

![mywebsite.corp after second modification](/content/images/2017/07/Screen-Shot-2017-07-10-at-17.55.35.png)

As you can see, you can use capture groups to capture URL parameters which you can use like in the previous example. Pretty handy!

This is just a handful of possibilities, I hope that you find 'em useful. Thanks for reading!
Bart Simons
Author

Bart Simons

Comments