"Will code for travel"

Search technical info
Shorten URL
Written: 2024-03-11 17:08:46 Last update: 2024-07-05 15:29:57

These days, many website using long query parameter to display a specific content, for example youtube video.

I have implemented this service using PHP in a shared hosting, the code may not be useful to everyone because each hosting may have different way. These are logic steps to create a web service to forward the shorten URL to long target URL.

  1. Use a short domain name (duh!) between 2 to 4 characters, eg: https://gue2.com
  2. Register the target URL to be shorten in database.
  3. Generate unique shorter ID, eg: '123'
  4. Use a logic to transform the URL, in my shared hosting using Apache, I use .htaccess
    For example a shorten URL 'https://gue2.com/123' to a target URL 'https://gue2.com/yt/view.php?id=123'
  5. Use JS in the shorten URL 'https://gue2.com/123' to add listener to 'DOMContentLoaded' and set 'window.location.href=target-URL' to immediately jump to target-URL

Example of .htaccess entry

RewriteEngine on

# rewrite for both with or without ending '/'
RewriteRule ^([a-zA-Z0-9_-]+)$ yt/view.php?shortenId=$1 [L,NC,QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/$ yt/view.php?shortenId=$1 [L,NC,QSA]

In usual case, we use this not only to shorten URL but also to add click-count for marketing and to get user's location.

Search more info