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:
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:
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:
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:
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 </Directory>
We are able to create an URL rewrite that functions like this:
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!