How to Shorten any URL with Apache/.htaccess
People prefer short links. The shorter the better. They are easier to remember, easier to type, and just look better than long, complicated URLs. For sites running on Apache servers, you can shorten long URLs with just a few lines of code added to Apache config or your site’s main .htaccess file. Here’s how to do it..
Shorten a single URL
Let’s say that your URL looks like this:
https://example.com/some/freakishly/long/url/that/you/want/to/shorten/
To shorten such an URL, add the following code to your main .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^/some/freakishly/long/url/that/you/want/to/shorten/ /shorturl/ [L]
</IfModule>
With that code in place, any requests for the long URL will be rewritten as /shorturl/
. Of course, you will want to replace both long and short paths with your own. As explained in my previous post, .htaccess Tip: Rewrite vs. Redirect, the key to rewriting is omitting the [R]
flag in the RewriteRule
. If you were to include the [R]
flag in the above example, the result would be an actual redirect to /shorturl/
, which most likely does not actually exist.
Shorten multiple URLs
What about shortening multiple URLs? Like for example, if we want to shorten WordPress’ default /page/123/
URLs to exclude the /page/
part. It’s the same basic concept, but with a little regular expression magic thrown in to account for the different URL variations. Consider the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^/page/([0-9]+)/?$ /$1/ [L]
</IfModule>
The trick here is twofold. First we are using some regex ([0-9]+)
to match any page number. Then we use the matched number in the rewrite by calling the result via $1
variable. So for example, if a visitor requests the following page:
https://example.com/page/24/
..the number 24
will be matched by ([0-9]+)
and then returned as the destination URL via $1
. So the result will be the URL rewritten like so:
https://example.com/24/
Again, if we were to include the [R]
flag (like [R,L]
in the RewriteRule
), the above example would redirect to the new URL instead of rewriting. This is an important concept when it comes to working with Apache’s mod_rewrite
.