Advertisement
  1. Web Design
  2. HTML/CSS
  3. HTML

Build Your Own URL Shortener With YOURLS

Scroll to top
Final product imageFinal product imageFinal product image
What You'll Be Creating

In this tutorial, I'll show you how to install your own open source, PHP-based URL shortener, called YOURLS.

The Benefit of URL Shorteners

URL shorteners reached their peak in usefulness just before Twitter began encoding all links with its t.co URL shortener. Up to that point, URL shorteners helped people tweet multiple links without using up their 140 characters. Today, every link in a tweet takes up a fixed number of characters regardless of length; using your own link shortener is now less important. Back then, Bit.ly was a popular choice.

The Bitly URL Shortener StatisticsThe Bitly URL Shortener StatisticsThe Bitly URL Shortener Statistics

However, there's still a benefit to using third-party link shorteners. For example, Google shows you statistics and traffic, and even generates a QR code for you to drive traffic to your link:

Googl URL Shortener with QR CodeGoogl URL Shortener with QR CodeGoogl URL Shortener with QR Code

If you want enhanced statistical tracking, running your own URL shortener can be very useful. For example, I wanted to better track which of my blog entries were driving referral traffic to specific affiliates. To do this, I needed my own solution.

Drawbacks of Hosting Your Own URL Shortener

There are a few caveats to hosting your own URL shortener:

  1. You will be eternally responsible for keeping the service up and running it, so that past links will continue to redirect properly.
  2. If your server goes down or times out, your links will break.
  3. If social media or web traffic for a shortcut URL spikes, your server will face heavy traffic requests.
  4. If you leave the service open to the public—which I don't recommend—there's a possibility of spammers and hackers abusing your service.
  5. There's a cost for having a domain to run your shortener, e.g. a dedicated .ly domain (optional, because of course you can use an existing sub-domain).

Open Source or Do It Yourself

I was initially tempted to write my own solution. However, a bit of searching turned up YOURLS. YOURLS is a PHP-based URL shortening service with decent statistical tracking and a variety of plugins. For this tutorial, I decided to write about using YOURLS rather than building from scratch.

By the way, if you're looking for a short domain, try using Domainr to find useful domains with two-letter extensions.

Installing YOURLS

Configure Your Server

I'm running YOURLS at Digital Ocean because it's inexpensive and offers fast SSD drives for hosting, but any LAMP-based server or cloud hosting provider will suffice. You can find my visual guide to installing a LAMP instance at Digital Ocean here.

Once you've got a server instance running, you can download the code for YOURLS here, or you can clone it from the public Git archive.

Installing the Code

Let's create a directory, download and unpack the code:

1
mkdir /var/www/yourls
2
cd /var/www/yourls
3
git clone https://github.com/YOURLS/YOURLS/archive/1.7.tar.gz
4
tar -zxvf 1.7.tar.gz 
5
mv YOURLS-1.7/ yourls

Create an Apache site configuration file:

1
sudo nano /etc/apache2/sites-available/yourls.conf

Paste in and customize the following site configuration:

1
<VirtualHost *:80>
2
   ServerName your-yourls-domain.com
3
   DocumentRoot /var/www/yourls
4
   DirectoryIndex index.php
5
   <Directory /var/www/yourls/>
6
      AllowOverride All
7
      Order Deny,Allow
8
      Allow from all
9
   </Directory>
10
</VirtualHost>

Enable the site and restart Apache:

1
sudo a2ensite yourls.conf 
2
sudo service apache2 reload

Let's create a MySQL database for YOURLS to use:

1
mysql -uroot -p

Create your database and permissions for YOURLS to use:

1
create database yourls;
2
grant all privileges on yourls.* TO "yourls_db_user"@"localhost" identified by "yourls-pwd";
3
flush privileges;
4
exit;

Configure the YOURLS Site

Now that our Apache site and MySQL database are available, let's configure the code a bit more.

Begin by copying the configuration sample to a live file and temporarily allow write permissions for the installation.

1
cd /var/www/yourls
2
cp ./user/config-sample.php ./user/config.php
3
chmod 0666  ./user/config.php 

Let's edit the file:

1
sudo nano ./user/config.php

First, configure your database settings based on how you configured MySQL above. You can follow along the configuration settings from the YOURLS site documentation:

1
/*
2
 ** MySQL settings - You can get this info from your web host
3
 */
4
5
/** MySQL database username */
6
define( 'YOURLS_DB_USER', 'your db user name' );
7
8
/** MySQL database password */
9
define( 'YOURLS_DB_PASS', 'your db password' );
10
11
/** The name of the database for YOURLS */
12
define( 'YOURLS_DB_NAME', 'yourls' );
13
14
/** MySQL hostname.
15
 ** If using a non standard port, specify it like 'hostname:port', eg. 'localhost:9999' or '127.0.0.1:666' */
16
define( 'YOURLS_DB_HOST', 'localhost' );
17
18
/** MySQL tables prefix */
19
define( 'YOURLS_DB_PREFIX', 'yourls_' );

Then, provide your chosen domain site name (the URL) and initial user passwords. Entering the passwords in plain text here is okay temporarily, because YOURLS will hash them in place.

1
/** YOURLS installation URL -- all lowercase and with no trailing slash.
2
 ** If you define it to "http://site.com", don't use "http://www.site.com" in your browser (and vice-versa) */

3
define( 'YOURLS_SITE', 'http://site.com' );

4


5
/** Username(s) and password(s) allowed to access the site. Passwords either in plain text or as encrypted hashes

6
 ** YOURLS will auto encrypt plain text passwords in this file

7
 ** Read http://yourls.org/userpassword for more information */

8
$yourls_user_passwords = array(

9
    'username' => 'password',

10
	'username2' => 'password2'	// You can have one or more 'login'=>'password' lines

11
	);

We also need to create an .htaccess file and ensure Apache mod_rewrite is active:

1
sudo a2enmod rewrite
2
sudo nano /var/www/yourls/.htaccess

Paste the default .htaccess file in:

1
# BEGIN YOURLS

2
<IfModule mod_rewrite.c>
3
RewriteEngine On
4
RewriteBase /
5
RewriteCond %{REQUEST_FILENAME} !-f
6
RewriteCond %{REQUEST_FILENAME} !-d
7
RewriteRule ^.*$ /yourls-loader.php [L]
8
</IfModule>
9
# END YOURLS

More details for configuring .htaccess and YOURLS are here.

Now, visit your YOURLS site administration at http://yourexampledomain.com/admin and walk through any configuration steps that it still requires.

YOURLS Install PageYOURLS Install PageYOURLS Install Page

Once the passwords are hashed and YOURLS is running properly, be sure to change permissions on the configuration file back to read only:

1
sudo chmod 0440 ./user/config.php 

Once you enter in a few shortcuts and begin receiving traffic, you should see something like this at your /admin path:

YOURLS Dashboard of ShortcutsYOURLS Dashboard of ShortcutsYOURLS Dashboard of Shortcuts

Build a Home Page

By default, there is no YOURLS home page. This is by design, to prevent spammers from abusing your service. 

I created a default index.php file to redirect to my consulting webpage. Visitors will only get this page when they enter my YOURLS URL without a proper shortcut:

1
<html>
2
<head>
3
    <META http-equiv="refresh" content="0;URL=http://lookahead.io">
4
  </head>
5
  <body bgcolor="#ffffff">
6
    <center>
7
Please visit our website <a href="http://lookahead.io">Lookahead Consulting</a>
8
    </center>
9
</body>
10
</html>

However, if you wish to offer a public shortcut page, copy sample-public-front-page.txt to index.php.

1
cp sample-public-front-page.txt index.php

Creating Shortcuts

Creating shortcuts is easy and should be self-explanatory. Here's an example of me creating a shortcut to my Tuts+ instructor profile:

Creating a shortened URL with YOURLSCreating a shortened URL with YOURLSCreating a shortened URL with YOURLS

YOURLS makes it easy to share your URL on Twitter and Facebook:

Share your shortened URLS via YOURLSShare your shortened URLS via YOURLSShare your shortened URLS via YOURLS

Traffic Statistics

Statistics are one of the most useful aspects built in to YOURLS. Here are general activity levels over time:

Traffic Statistics History with YOURLSTraffic Statistics History with YOURLSTraffic Statistics History with YOURLS

And, here's geographical referral information:

Traffic by Geography with YOURLSTraffic by Geography with YOURLSTraffic by Geography with YOURLS

Here's the reason I chose YOURLS: to get detailed traffic numbers on which pages were driving the most affiliate referrals.

Detailed Referral Activity with YOURLSDetailed Referral Activity with YOURLSDetailed Referral Activity with YOURLS

Over time, this will help me tune the placement of my affiliate advertising.

Doing More with YOURLS

There is also an extensive group of YOURLS Plugins and an API to explore. For example, there are Memcached and QR Code plugins, among others.

YOURLS is a well-configured, tight piece of PHP code for running your own URL shortener. I hope you've found this useful.

Please post any comments, corrections or additional ideas below. You can browse my other Tuts+ tutorials on my instructor page, or follow me on Twitter @reifman.

Related Links

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Web Design tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.