1. Code
  2. Ruby
  3. Ruby on Rails

How to Create Your Own Local Premium URL Shortener Service

Scroll to top

You will encounter some very long URLs (Uniform Resource Locators) on the internet. Many sites put information about your visit into the URL: items like language, location, identification, reference codes for specials, and many other items. This makes for very long URLs.

Premium URL Shortener on CodeCanyonPremium URL Shortener on CodeCanyonPremium URL Shortener on CodeCanyon
Premium URL Shortener on CodeCanyon

Premium URL Shortener on Code Canyon is a way to make long URLs shorter. In this tutorial, I will show you how to set up your own URL shortener on your system and how to use it.

What Is a URL Shortener?

You use a URL whenever you browse the internet. It identifies the particular web page and content. Since these can often contain parameters for a form or search engine, these URLs can get quite large.

1
https://tutsplus.com/tutorials/search/How%20to%20Draw%20Animals:%20Horses,%20Their%20Anatomy%20and%20Poses

This URL is for searching the Tuts+ website for the string “How to Draw Animals: Horses, Their Anatomy and Poses”. This string is 74 characters long. I’ve seen URLs that are over 200 characters long.

1
https://bit.ly/2oO8BqO

When you use a URL shortening service, like bit.ly, you get a much shorter URL. The same URL is now 15 characters long. When someone browses this link, the bit.ly server redirects the browser to the full URL. The extra lookup on a different URL does delay the site load time, but not much.

Installing Docker

The easiest way to create a local server is to use a virtualized environment. But running a full system virtualizer is very resource intensive. Docker is a minimal virtualizer for terminal-based systems. You can run a Docker container (a small unix server) using fewer system resources.

To run containers on your system, you will need to install Docker. Select the proper download for your operating system from the Docker website.

With Docker installed, you need to prepare your system to look for the web service you will be creating. To do this, you will need to change a system file. In the /etc/hosts file for Linux or macOS systems and in the c:\windows\System32\drivers\etc\lmhosts file for a Windows system, put this statement:

1
127.0.0.1 s.dev

This change will make all references to http://s.dev go to the local system. This is done to give the service a proper hostname before trying to configure it.

To create your development area, create a directory and place the Premium URL Shortener zip file in it and expand it. You should then have this directory structure:

Directory StructureDirectory StructureDirectory Structure
Directory Structure

This is the documentation with the file main.zip. Expand this file also. Once you expand it, you should have this directory structure:

Directory Structure with CodeDirectory Structure with CodeDirectory Structure with Code
Directory Structure with Code

The main.zip file contains all the source code files and resources for the service. This will be the directory you will add to the Docker instance.

Now you need to get the Docker LAMP stack from fauria. With Docker running, type the following into a terminal:

1
docker pull fauria/lamp

This will download the Fauria LAMP (Linux, Apache, MySQL, and PHP) stack to your Docker installation. Once downloaded, you can create the container with:

1
docker run --rm --name linkshort -p 80:80 -e LOG\_STDOUT=true -e LOG\_STDERR=true -e LOG\_LEVEL=debug -v {{service source directory}}:/var/www/html fauria/lamp

Replace the {{service source directory}} with the complete path to the directory that contains all the source files and resources. This command creates a container named linkshort that works on port 80 and gives all the error and log messages to standard out.

Right now, every time you stop and relaunch the container, you will lose all your information. You need to move the database information to your source code directory to preserve it with each reboot. In a terminal window, perform these commands:

1
docker exec -i -t linkshort bash
2
mkdir /var/www/html/data
3
cp -R /var/lib/MySQL/* /var/www/html/data
4
exit

The first command opens a bash shell to the container. The second command creates the directory data in your source code directory. The container sees the source code directory as the /var/www/html directory. The third command copies the database information to that directory. The exit command gets you out of the container. 

Now stop the container using:

1
docker stop linkshort

You will use this command each time you want to stop the container.

Now, to restart the container using the proper data directory, use this command:

1
docker run --rm --name linkshort -p 80:80 -e LOG\_STDOUT=true -e LOG\_STDERR=true -e LOG\_LEVEL=debug -v {{service source directory}}:/var/www/html -v {{service source directory}}/data:/var/lib/mysql fauria/lamp

This time you created the container with the MarianDB server using the database data now stored on your computer. This is the command you will use to launch the service. I use the keyboard expander Typinator to type this out for me.

Now, the database for the URL shortener needs to be created. You will need to open a shell in to the container as well. In a new terminal instance, type the following command:

1
docker exec -i -t linkshort bash

This command creates the bash shell into the container. If you need to adjust something in the container, this is the command you will use. Next, open a command shell into the MarianDB program:

1
mysql -u root

Now, you can create databases in MarianDB and grant permissions to the web server to access it:

1
create database urlshort;
2
create user 'www-data'@'localhost' identified by '{{password}}';
3
grant all on urlshort.\* to 'www-data'@'localhost';
4
quit;

The {{password}} needs to be set to the password you want to give to the user of the database. Remember this as you will use it to configure the service.

With the service running in the container, open your web browser to http://s.dev.

Requirement Check PageRequirement Check PageRequirement Check Page
Requirement Check Page

If you did the configuration, you should see this page. This page shows the requirements for the URL Shortener service and the status of your setup. By using the fauria container in Docker, you already have all the dependencies met. Click the blue button at the bottom of the page.

Database Configuration PageDatabase Configuration PageDatabase Configuration Page
Database Configuration Page

The next page shown is the configuration file creator for the service. This page allows you to give the program the name and password for the database you created earlier.

Database Configuration Page DetailsDatabase Configuration Page DetailsDatabase Configuration Page Details
Database Configuration Page Details

You need to fill in these fields as shown above. The Database Host is the localhost for the container. The Database Name is urlshort, which you created in the setup. The Database User is www-data, and the password is the one you assigned in the initial database setup. The Database Prefix is the beginning name for each database created for the service. I used short_. The installation program sets the Security Key. Keep a copy of the key given for future reference.

If you were to install this on a Virtual Private Server (VPS), these values would be according to that service. Some will be the same, and some will change.

With the proper information in place, press the blue button at the bottom of the page to go to step 3.

Basic Configuration PageBasic Configuration PageBasic Configuration Page
Basic Configuration Page

The Basic Configuration screen allows you to set the admin user name, email, and password. Set these to the values that pertain to you. The Site URL needs to be set to http://s.dev as you set up in your hosts file earlier. Once set, press the blue button at the bottom of the screen.

Installation Complete PageInstallation Complete PageInstallation Complete Page
Installation Complete Page

The next screen tells you that the service is now set up. Press the blue button that says Delete install.php. This is a security feature for using on a real web server, but isn’t needed for a local install. However, the installation will not finish until you have done it.

Premium URL Shortener Front PagePremium URL Shortener Front PagePremium URL Shortener Front Page
Premium URL Shortener Front Page

Congratulations—the service is functional! You should see the above screen. If you give a long URL into the input field named Paste a long url and then press the blue button Shorten, you will get a shortened URL to use. The URL will also be in the database for future reference. This feature makes a great bookmarker.

Using the API

Now that you have your URL shortener service running, you will want to make good use of it. But always opening a web page, even a local one, will slow you down. You need to make it faster. That’s where using the API (Application Programming Interface) is helpful. You can refer to the full documentation for the API.

With the service running, open the page http://s.dev/user/settings.

Account Settings PageAccount Settings PageAccount Settings Page
Account Settings Page

You have to log in to your account to see this page. At the bottom right in the sidebar, you will see Your API Key: with an alpha-numeric number. Copy that number and save it. This number gives access to the API.

To make use of the API, you can create a Ruby program to access it. On macOS and Linux, Ruby is usually pre-installed. On Windows, you will have to install it.

The minimal program in Ruby for creating a short link is:

1
require 'net/http'
2
require 'json'
3
4
API = '{YourAPIKey}'
5
6
short = JSON.parse(Net::HTTP.get('s.dev', '/api?api=' + API + '&url=' + ARGV[0]))
7
if short["error"] == 0 then
8
  print short["short"]
9
else
10
  print "An error happened:  "
11
  print short["error"]
12
  print "\n"
13
end

Save the script to a file named shortener.rb, replace {YourAPIKey} with the API key you copied earlier, and run the following in the command line:

1
ruby shortener.rb 'google.com'

You should get a shortened link for that URL. This creates the shortened URLs, but is still not convenient.

Creating a PopClip Extension

On the Mac, PopClip is a great little program for processing highlighted text. To make creating the shortened links easier, you will create a PopClip extension. I’m not going to explain everything about making an extension, but you can read about the mechanics of doing it in my tutorial PopClip: Scripting Extensions.

Create a PopClip extension called PremiumURLShortener.popclipext. Use the following for the Config.plist file inside the extension directory:

1
<?xml version="1.0" encoding="UTF-8"?>
2
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
<plist version="1.0">
4
<dict>
5
    <key>Actions</key>
6
	<array>
7
		<dict>
8
			<key>After</key>
9
			<string>paste-result</string>
10
            <key>Image File</key>
11
            <string>PremiumURLShortener.png</string>
12
            <key>Script Interpreter</key>
13
            <string>/usr/bin/ruby</string>
14
            <key>Shell Script File</key>
15
            <string>PremiumURLShortener.rb</string>
16
            <key>Title</key>
17
            <string>Shortener</string>
18
		</dict>
19
	</array>
20
	<key>Options</key>
21
	<array>
22
		<dict>
23
			<key>Option Identifier</key>
24
			<string>apikey</string>
25
			<key>Option Type</key>
26
			<string>string</string>
27
			<key>Option Label</key>
28
			<string>API Key: </string>
29
		</dict>
30
	</array>
31
	<key>Credits</key>
32
	<array>
33
	    <dict>
34
	        <key>Name</key>
35
	        <string>Richard Guay</string>
36
	        <key>Link</key>
37
	        <string>http://customct.com</string>
38
	    </dict>
39
	</array>
40
	<key>Extension Description</key>
41
	<string>Create shortened URLs with PremiumURLShortener locally</string>
42
	<key>Extension Identifier</key>
43
	<string>com.customct.popclip.extension.premiumurlshortener</string>
44
	<key>Extension Name</key>
45
	<string>Shortener</string>
46
	<key>Required Software Version</key>
47
	<integer>701</integer>
48
</dict>
49
</plist>

Then create the script file for the extension called PremiumURLShortener.rb and place this code in it:

1
#!/usr/bin/ruby

2
3
require 'net/http'
4
require 'json'
5
6
Encoding.default_internal = Encoding::UTF_8
7
Encoding.default_external = Encoding::UTF_8
8
9
input = ENV['POPCLIP_TEXT'].to_s.strip()
10
API = ENV['POPCLIP_OPTION_APIKEY'].to_s.strip()
11
12
short = JSON.parse(Net::HTTP.get('s.dev', '/api?api=' + API + '&url=' + input))
13
if short["error"] == 0 then
14
  print short["short"]
15
else
16
  print "An error happened:  "
17
  print short["error"]
18
  print "\n"
19
end

When you load the new extension, it will ask for the API key. Once you give it the API key and press Okay, it is usable in PopClip.

Shortening a URL with PopClipShortening a URL with PopClipShortening a URL with PopClip
Shortening a URL with PopClip

When you select a link, PopClip will open with a list of options. You then select the Shortener option. It will think for a while and then paste the proper shortened URL. The full extension is in the download for this tutorial. Now, you are ready to do many more!

Conclusion

Not only do you now have a private URL shortener, you also know how to make use of Docker for running local containers, an easy way to keep track of URLs that you use, and a way to create the shortened links. 

You can use the Ruby script with Alfred 3 or Keyboard Maestro as well. Enjoy using your new service and experimenting with its other features.

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 Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.