On one of my sites I wanted to allow my users to enter a short URL to go to a page with a longer URL. For example, I wanted them to type a short url like this: example.com/m/1234567 instead of a long url like this: example.com/membership.php?id=1234567
To do this, I added my .htaccess file in my public_html folder
# RewriteEngine On RewriteBase / RewriteRule m(/)(.+)$ /membership.php?id=$2 [L] #
If I understand how this works correctly, the first part of the RewriteRule – m(/)(.+)$
– describes the url coming in… the one my users will type in or click on.
Each parenthesis pair represents a variable, $1 and $2, that can be used in the second path/url – /membership.php?id=$2
The first set of parenthesis tell the RewriteRule to look for a forward slash after an ‘m’ in the URL. The value found in the first path/url where the second set of parenthesis are located will replace the $2
in the second path/url. I think the .+
just lets the RewriteRule know that it can be any number of characters after the slash in the URL.
So, in my earlier example, the $2 will end up being 1234567 and will make the url what we wanted – /membership.php?id=1234567
If I’m mistaken about any part of this, please let me know in the comments below. I got this working the way it’s written here, but I’d really like to understand why it’s working better.