How to Create Your Own Local Premium URL Shortener Service

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.

How to Create Your Own Local Premium URL Shortener Service

How to Create Your Own Local Premium URL Shortener Service

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.

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.

http://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:windowsSystem32driversetclmhosts file for a Windows system, put this statement:

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:

How to Create Your Own Local Premium URL Shortener Service

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

How to Create Your Own Local Premium URL Shortener Service

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:

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:

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:

docker exec -i -t linkshort bash
mkdir /var/www/html/data
cp -R /var/lib/MySQL/* /var/www/html/data
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:

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:

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:

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:

mysql -u root

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

create database urlshort;
create user 'www-data'@'localhost' identified by '{{password}}';
grant all on urlshort.* to 'www-data'@'localhost';
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.

How to Create Your Own Local Premium URL Shortener Service

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.

How to Create Your Own Local Premium URL Shortener Service

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.

How to Create Your Own Local Premium URL Shortener Service

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.

How to Create Your Own Local Premium URL Shortener Service

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.

How to Create Your Own Local Premium URL Shortener Service

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.

How to Create Your Own Local Premium URL Shortener Service

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.

How to Create Your Own Local Premium URL Shortener Service

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:

require 'net/http'
require 'json'

API = '{YourAPIKey}'

short = JSON.parse(Net::HTTP.get('s.dev', '/api?api=' + API + '&url=' + ARGV[0]))
if short["error"] == 0 then
  print short["short"]
else
  print "An error happened:  "
  print short["error"]
  print "n"
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:

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:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Actions</key>
	<array>
		<dict>
			<key>After</key>
			<string>paste-result</string>
            <key>Image File</key>
            <string>PremiumURLShortener.png</string>
            <key>Script Interpreter</key>
            <string>/usr/bin/ruby</string>
            <key>Shell Script File</key>
            <string>PremiumURLShortener.rb</string>
            <key>Title</key>
            <string>Shortener</string>
		</dict>
	</array>
	<key>Options</key>
	<array>
		<dict>
			<key>Option Identifier</key>
			<string>apikey</string>
			<key>Option Type</key>
			<string>string</string>
			<key>Option Label</key>
			<string>API Key: </string>
		</dict>
	</array>
	<key>Credits</key>
	<array>
	    <dict>
	        <key>Name</key>
	        <string>Richard Guay</string>
	        <key>Link</key>
	        <string>http://customct.com</string>
	    </dict>
	</array>
	<key>Extension Description</key>
	<string>Create shortened URLs with PremiumURLShortener locally</string>
	<key>Extension Identifier</key>
	<string>com.customct.popclip.extension.premiumurlshortener</string>
	<key>Extension Name</key>
	<string>Shortener</string>
	<key>Required Software Version</key>
	<integer>701</integer>
</dict>
</plist>

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

#!/usr/bin/ruby

require 'net/http'
require 'json'

Encoding.default_internal = Encoding::UTF_8
Encoding.default_external = Encoding::UTF_8

input = ENV['POPCLIP_TEXT'].to_s.strip()
API = ENV['POPCLIP_OPTION_APIKEY'].to_s.strip()

short = JSON.parse(Net::HTTP.get('s.dev', '/api?api=' + API + '&url=' + input))
if short["error"] == 0 then
  print short["short"]
else
  print "An error happened:  "
  print short["error"]
  print "n"
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.

How to Create Your Own Local Premium URL Shortener Service

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.