How to Install Shlink URL Shortener on Ubuntu 18.04 Server

Shlink is an open-source self-hosted URL shortener, which allows you to shorten URLs and serve them under your own short domain. Using your own URL shortner service instead of third-party service like bit.ly can increase brand awareness. This tutorial will be showing you how to install Shlink on Ubuntu 18.04 with Apache or Nginx web server.

install shlink on ubuntu_ self hosted url shortener

Shlink Features

  • Visit stats: Track all the visits to your short URLs, including stats like location, browser or referrer.
  • Email tracking: Generate a 1px transparent image that can be used to track emails.
  • Third party integrations: Easily make third party tools use shlink to shorten URLs by using a single-request API endpoint.
  • Custom Slugs: Make your shortened URLs use a custom slug to easily identify campaigns.
  • QR codes: Generate QR codes on the fly pointing to your short URLs
  • Previews: Get previews in image format for any short URL
  • Tags: Tag your short URLs and classify them for later analytics
  • Limited access: Limit access to short URLs, by date range and/or maximum number of visits.
  • Third-party imports: Import your existing short URLs from third parties like bit.ly.
  • Command-line and web interface.

Prerequisites of installing Shlink on Ubuntu 18.04 Server

Shlink is written in PHP and relies on MySQL/MariaDB or PostgreSQL database server, so you need to set up a LAMP stack or LEMP stack. If you prefer Apache web server, then set up LAMP stack.

If you prefer Nginx web server, then set up LEMP stack.

You also need a domain name. I registered my domain name from NameCheap because the price is low and they give whois privacy protection for free. In this tutorial, I use my lnux.be domain name as an example. Without further ado, let’s install Shlink on Ubuntu 18.04 server.

Step 1: Download Shlink onto Your Ubuntu 18.04 Server

Go to the Shlink Github page to see the latest stable version. You can download the latest stable version (2.6.2) by executing the following command on your server.

wget https://github.com/shlinkio/shlink/releases/download/v2.6.2/shlink2.6.2_php8.0_dist.zip

Note: If a new version comes out, simply replace 2.6.2 with the new version number.

The file will be saved as shlink2.6.2_php8.0_dist.zip. Use unzip command to unzip it to /var/www/ directory.

sudo apt install unzip

sudo mkdir -p /var/www/

sudo unzip shlink2.6.2_php8.0_dist.zip -d /var/www/

Now the files are stored under /var/www/shlink2.6.2_php8.0_dist/, we rename it to make it simpler.

sudo mv /var/www/shlink2.6.2_php8.0_dist/ /var/www/shlink

Then make the web server user (www-data) as the owner of this directory.

sudo chown -R www-data:www-data /var/www/shlink/

Step 2: Create a MariaDB Database and User for Shlink

Now we need to log in to the MariaDB console and create a database and user for Shlink. By default, the MariaDB package on Ubuntu uses unix_socket to authenticate user login, which basically means you can use the username and password of the OS to log into the MariaDB console. So you can run the following command to login without providing MariaDB root password.

sudo mysql -u root

Next, create a new database for Shlink using the following command. This tutorial names it shlink, you can use whatever name you like for the database.

CREATE DATABASE shlink;

The following command will create a database user and password, and at the same time grant all permission of the new database to the new user so later on Shlink can write to the database. Replace red texts with your preferred database name, username, and password.

GRANT ALL ON shlink.* TO 'shlink'@'localhost' IDENTIFIED BY 'password';

Flush privileges table and exit MariaDB console.

FLUSH PRIVILEGES;

EXIT;

Step 3: Install PHP8.0 and Some Extensions

Since we downloaded the PHP 8 version of Shlink, we need to install PHP8.  Ubuntu 18.04 repository includes PHP7.2. To install PHP8.0 on Ubuntu 18.04, we need to add a PPA.

sudo apt install software-properties-common

sudo add-apt-repository ppa:ondrej/php -y

Then install PHP8.0 and the extensions required by Shlink.

sudo apt install php-apcu php8.0 php8.0-fpm php8.0-mysql php8.0-gd php8.0-common php8.0-curl php8.0-intl php8.0-gmp php8.0-xml

If you use Apache web server, you need to run the following commands to make it use PHP8.0-FPM.

sudo a2dismod mpm_prefork
sudo a2enmod mpm_event proxy_fcgi setenvif
sudo a2enconf php8.0-fpm

Then restart Apache.

sudo systemctl restart apache2

Step 4: Run the Shlink Install Script

Go to the /var/www/shlink/bin/ directory.

cd /var/www/shlink/bin/

There’s a PHP script named install, we run the script as the www-data user.

sudo -u www-data php8.0 ./install

Then the setup wizard will ask you to enter database details. So I choose MariaDB as the database type, then enter the database name, user and password. The host is localhost and the port is 3306.

shlink-install-script-wizard-command-line

Next, enter the default domain for your URL shortener and select the scheme type (https)

shlink-self-hosted-url-shortner-ubuntu-18.04

Then configure the redirects. When visitors hit my Shlink’s base URL (https://lnux.be), they will be redirected to my website. You can also create a custom URL for 404 not found page. In this tutorial, I simply press Enter to accept the default.

shlink redirects

Finally, configure the application. I simply press Enter to use the default settings.

install-shlink-on-ubuntu-18.04-server-apache-nginx

Step 5: Create Apache Virtual Host or Nginx Config File for Shlink

Apache

If you use Apache web server, create a virtual host for Shlink.

sudo nano /etc/apache2/sites-available/shlink.conf

Put the following text into the file. Replace lnux.be with your real domain name and don’t forget to set DNS A record for it.

<VirtualHost *:80>
  ServerName lnux.be
  DocumentRoot /var/www/shlink/public

  ErrorLog ${APACHE_LOG_DIR}/shlink_error.log
  CustomLog ${APACHE_LOG_DIR}/shlink_access.log combined

  <Directory /var/www/shlink/public>
    Options FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>

</VirtualHost>

Save and close the file. Then enable this virtual host with:

sudo a2ensite shlink.conf

Reload Apache for the changes to take effect.

sudo systemctl reload apache2

Nginx

If you use Nginx web server, create a virtual host for Shlink.

sudo nano /etc/nginx/conf.d/shlink.conf

Put the following text into the file. Replace lnux.be with your real domain name and don’t forget to set DNS A record for it.

server {
   listen 80;
   listen [::]:80;
   server_name lnux.be;

   root /var/www/shlink/public;
   error_log /var/log/nginx/shlink.error;
   access_log /var/log/nginx/shlink.access;

   index index.php index.html index.htm index.nginx-debian.html;

   location / {
     # try to serve file directly, fallback to app.php
     try_files $uri /index.php$is_args$args;
   }

   # redirect some entire folders
     rewrite ^/(vendor|translations|build)/.* /index.php break;

   location ~ \.php$ {
     fastcgi_split_path_info ^(.+\.php)(/.+)$;
     fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
     fastcgi_index index.php;
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
     include fastcgi_params;
   }

}

Save and close the file. Then test Nginx configuration.

sudo nginx -t

If the test is successful, reload Nginx for the changes to take effect.

sudo systemctl reload nginx

Step 6: Enabling HTTPS

To encrypt the HTTP traffic, we can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. Run the following command to install Let’s Encrypt client (certbot) on Ubuntu 18.04 server.

sudo apt install certbot

If you use Apache, install the Certbot Apache plugin.

sudo apt install python3-certbot-apache

And run this command to obtain and install TLS certificate.

sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d lnux.be

If you use Nginx, then you also need to install the Certbot Nginx plugin.

sudo apt install python3-certbot-nginx

Next, run the following command to obtain and install TLS certificate.

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d lnux.be

Where

  • --nginx: Use the nginx plugin.
  • --apache: Use the Apache plugin.
  • --agree-tos: Agree to terms of service.
  • --redirect: Force HTTPS by 301 redirect.
  • --hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
  • --staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.

The certificate should now be obtained and automatically installed.

shlink https

Step 7: Creating Short Links

First, you need to create an API key with the following command.

sudo -u www-data php8.0 /var/www/shlink/bin/cli api-key:generate

Then go to https://app.shlink.io/ to add your server.

shlink create short link

Once you add your server, you can create short links.

shlink create short url

Note that this is just a web client. Short URLs are stored on your own server.

You can also generate short URLs from command line on your server.

sudo -u www-data /var/www/shlink/bin/cli short-url:generate

List short URLs.

sudo -u www-data /var/www/shlink/bin/cli short-url:list

Run the following command to see the help message.

sudo -u www-data php /var/www/shlink/bin/cli

Wrapping Up

I hope this tutorial helped you install Shlink on Ubuntu 18.04 server.You may also want to learn how to use multiple versions of PHP on Ubuntu.

As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂

Rate this tutorial
[Total: 3 Average: 5]

22 Responses to “How to Install Shlink URL Shortener on Ubuntu 18.04 Server

  • vanhussen
    5 years ago

    Work for me.. Thank you!

  • vanhussen
    5 years ago

    What is different shlink-web-client v2.1.1 with shlink_1.18.1? Becouse when I access my server, 404
    Page not found.
    The page you requested could not be found.

    I see some people can make graphic pie on sites address.

    • Xiao Guo An (Admin)
      5 years ago

      Shlink is the server. Shlink-web-client is the client. You can self host the web client if you want to. You use the web-client or command line client to manage short links. The main domain name like lnux.be isn’t a short link.

  • After playing with your first url shortener url, you might enjoy and want to use other urls for marketing branding. You can enter more domains / sub domains you’ve pointed to the server ip

    For nginx – add multiple domains on:

    sudo nano /etc/nginx/conf.d/shlink.conf

    Edit server name line:

    server {
       listen 80;
       listen [::]:80;
       server_name example1.com example2.com link.example3.com go.yourdomain.com ;
    ...
    

    CTRL-X (to exit) and Y (to save)

    Then check to make sure it’s good:

    sudo nginx -t

    Reload nginx:

    sudo systemctl reload nginx

    Then rerun certbot with your additional domains:

    sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d example1.com -d example2.com -d link.example3.com -d go.yourdomain.com

    Thanks again for the tutorial LinuxBabe!

  • error for me:

    sudo -u www-data php ./install

    PHP Warning: require(/var/www/html/shlink/bin/../vendor/shlinkio/shlink-installer/bin/run.php): failed to open stream: No such file or directory in /var/www/html/shlink/bin/install on line 11

  • Quang Mai
    4 years ago

    Ni hao Xiao,

    I follow your instruction and have the same error code as @carlos above:

    Code:

    sudo -u www-data php ./install
    PHP Parse error:  syntax error, unexpected '$isUpdate' (T_VARIABLE), expecting ',' or ')' in /var/www/shlink/vendor/shlinkio/shlink-installer/bin/run.php on line 12
    

    Do you have any ideas? Thanks

    • Xiao Guoan (Admin)
      4 years ago

      The latest Shlink now requires PHP7.4. I just updated this article to include instructions to install PHP7.4.

      You need to run the install script with PHP7.4 like this:

      sudo -u www-data php7.4 ./install
  • Massimiliano
    4 years ago

    I followed the installation through the official documentation and I managed to have Shlink on my VPS.

    I have created a public folder that everyone can reach to manage the links and I can access it to see which links I have generated and to generate others.

    The problem is that the redirect system behind it does not work, for example I created “massifor.me/pc” which should redirect to my blog (pcgenius.org), in the command line I see the link and I also see it from webclient however when I click on it it says “Oops! We could not find requested route.”, I don’t know what it depends on.

    Php modules are all there, the wordpress sites that I have on the same machine work, do you have any ideas?
    I’m under Ubuntu, Apache, Php 7.4.5 and I’m using virtual hosts

  • Thank you for the tutorial! I’m trying to make it work with Swoole (as per their recommendation) but never managed to do so; it only listens to 8080 port, and I found no way to set up SSL without using a real webserver like apache or nginx, and the web client was never able to find the backend lol. Not sure if I should use a reverse proxy as a frontend (why Swoole if I’m using apache frontend anyways lol). Amazing script without doubt, but what a pity that it’s so insufficiently documented…

    • Alejandro Celaya Alastrué
      4 years ago

      You guessed right. When serving the app with swoole you should put an apache or nginx in front of it as a reverse proxy.

      There are undocumented ways to change the port, and swoole supports SSL, but the process is more complex, so it’s not worth it.

      Just use a well known web server as proxy 🙂

      I’ll make sure to get the docs updated to notice this. It’s absolutely not clear enough and can be confusing.

  • Hi Guys, just in case some one needs to know the exact location of the clicks run:

    sudo /var/www/shlink/bin/cli visit:locate 

    That after installing the new version which adds geo-location.

    You can make a cron job for that to be made automatically adding -q flag. That flag will avoid populating the cron logs.

    • CNXSoft
      3 years ago

      Thanks for that. I’m logged in as www-data so I had to use:

      sudo -u www-data php7.4 /var/www/shlink/bin/cli visit:locate 
  • Alejandro Celaya
    4 years ago

    Thanks a lot for spreading the word. Really good tutorial 🙂

  • how do i update from shlink v2.6.0 to v6.0.1
    i tried doing the way stated on the shlink website but after running the bin/update tool and restarting the VPS it just stops working when I visit the page it is just blank can anyone help

    • MasterYoda
      3 years ago

      You can follow this guide

      https://shlink.io/documentation/update-your-instance/

      • That is what i followed but after it was done my instance just showed a blank page

        • MasterYoda
          3 years ago

          Have you added the errorlog line to your apache/nginx config? is yes, can you please post the logs from there?

          can you try doing the permissions for www-data again?

          are you using swoole OR webserver?

        • MasterYoda
          3 years ago

          can you please check this and see if the solution here works for you?

          https://github.com/shlinkio/shlink/issues/1056#issuecomment-804511307

        • Utsav
          3 years ago

          Hi
          i am using Nginx
          therefore https://github.com/shlinkio/shlink/issues/1056#issuecomment-804511307, does not help me as it uses swoole
          i have tried to

          chown

          to www-data again but that seemed to do nothing

  • Saved as a favorite, I like your blog!

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here