Ricerca nel sito web

Come installare Shlink URL Shortener con Nginx su Ubuntu 20.04


Su questa pagina

  1. Prerequisiti
  2. Per iniziare
  3. Installa il server LEMP
  4. Crea database Shlink
  5. Scarica Shlink
  6. Installa Shlink
  7. Configura Nginx per Shlink
  8. Conclusione

Shlink è un accorciatore di URL open source e self-hosted scritto in PHP. Viene utilizzato per generare e gestire URL brevi dalla riga di comando. Ti consente di tenere traccia di tutte le visite dei tuoi URL brevi, inclusi posizione, browser o referrer. Può essere integrato con strumenti di terze parti utilizzando l'API Shlink. Fornisce un'interfaccia a riga di comando per abbreviare gli URL.

In questo tutorial, ti mostrerò come installare Shlink su Ubuntu 20.04.

Prerequisiti

  • Un server che esegue Ubuntu 20.04.
  • Un nome di dominio valido indicato con l'IP del tuo server.
  • Sul server è configurata una password di root.

Iniziare

Innanzitutto, aggiorna i pacchetti di sistema alla versione aggiornata eseguendo il seguente comando:

apt-get update -y

Una volta aggiornati tutti i pacchetti, puoi procedere al passaggio successivo.

Installa il server LEMP

Innanzitutto, installa Nginx, PHP, MariaDB e altri pacchetti richiesti con il seguente comando:

apt-get install nginx mariadb-server php-apcu php7.4 php7.4-fpm php7.4-mysql php7.4-gd php7.4-common php7.4-curl php7.4-intl php7.4-gmp php7.4-xml php-dev php-pear unzip -y

Una volta installati tutti i pacchetti, puoi procedere al passaggio successivo.

Crea un database Shlink

Shlink utilizza MariaDB come backend del database. Quindi dovrai creare un database e un utente per Shlink. Innanzitutto, connettiti a MariaDB con il seguente comando:

mysql

Una volta connesso, crea un database e un utente con il seguente comando:

MariaDB [(none)]> CREATE DATABASE shlink;
MariaDB [(none)]> GRANT ALL ON shlink.* TO 'shlink'@'localhost' IDENTIFIED BY 'password';

Successivamente, scarica i privilegi ed esci da MariaDB con il seguente comando:

MariaDB [(none)]> FLUSH PRIVILEGES;
MariaDB [(none)]> EXIT;

Scarica Shlink

Innanzitutto, scarica l'ultima versione di Shlink dalla loro pagina di download ufficiale:

wget https://github.com/shlinkio/shlink/releases/download/v2.7.1/shlink2.7.1_php7.4_dist.zip

Una volta completato il download, decomprimere il file scaricato con il seguente comando:

unzip shlink2.7.1_php7.4_dist.zip

Successivamente, sposta la directory estratta nella directory root web di Nginx:

mv shlink2.7.1_php7.4_dist /var/www/html/shlink

Quindi, imposta l'autorizzazione e la proprietà appropriate con il seguente comando:

chown -R www-data:www-data /var/www/html/shlink/
chmod -R 755 /var/www/html/shlink/

Installa Shlink

Successivamente, esegui il seguente comando per avviare l'installazione:

sudo -u www-data php7.4 /var/www/html/shlink/bin/install

Ti verrà chiesto di selezionare il database come mostrato di seguito:

 Welcome to Shlink!!
 This tool will guide you through the installation process.

DATABASE
========

 Select database type [MySQL]:
  [0] MySQL
  [1] MariaDB
  [2] PostgreSQL
  [3] MicrosoftSQL
  [4] SQLite
 > 1

Scegli qualsiasi opzione e premi Invio. Ti verrà chiesto di fornire il nome del database come mostrato di seguito:

 Database name [shlink]:
 > 

Fornisci il nome del tuo database o premi Invio per scegliere l'impostazione predefinita. Ti verrà chiesto di fornire l'host del database:

 Database host [localhost]:
 > 

Fornisci l'host del tuo database o premi Invio per scegliere l'impostazione predefinita. Ti verrà chiesto di fornire la porta del database:

 Database port [3306]:
 > 

Fornisci la porta del tuo database o premi Invio per scegliere l'impostazione predefinita. Ti verrà chiesto di fornire il nome utente del tuo database:

 Database username:
 > shlink

Fornisci il nome utente del tuo database e premi Invio. Ti verrà chiesto di fornire la tua password utente del database:

 Database password:
 > password

Fornisci la tua password utente del database e premi Invio. Ti verrà chiesto di fornire un socket Unix.

 Unix socket (leave empty to not use a socket):
 > 

Lascialo vuoto e premi Invio. Ti verrà chiesto di fornire il nome di dominio:

URL SHORTENER
=============

 Default domain for generated short URLs:
 > shlink.linuxbuz.com

Fornisci il tuo nome di dominio e premi Invio. Ti verrà chiesto di selezionare lo schema:

 Select schema for generated short URLs [http]:
  [0] http
  [1] https
 > 0

Seleziona un'opzione e premi Invio. Ti verrà chiesto di convalidare URL lunghi:

 Do you want to validate long urls by 200 HTTP status code on response? (yes/no) [yes]:
 > 

Scegli l'opzione predefinita e premi Invio. Ti verrà chiesto di fornire la lunghezza degli shortcode generati:

 What is the default length you want generated short codes to have? (You will still be able to override this on every created short URL) [5]:
 > 

Scegli il valore predefinito e premi Invio. Dovresti vedere il seguente output:

 Do you want Shlink to resolve the short URL title based on the long URL 's title tag (if any)? Otherwise, it will be kept empty unless explicitly provided. (yes/no) [no]:
 > 

Seleziona la risposta predefinita e premi Invio. Dovresti vedere il seguente output:

 Provide a GeoLite2 license key. (Leave empty to use default one, but it is strongly recommended to get your own. Go to https://shlink.io/documentation/geolite-license-key to know how to get it):
 > 

Lascialo vuoto e premi Invio. Dovresti vedere il seguente output:

 What kind of redirect do you want your short URLs to have? [All visits will always be tracked. Not that good for SEO.]:
  [302] All visits will always be tracked. Not that good for SEO.
  [301] Best option for SEO. Redirect will be cached for a short period of time, making some visits not to be tracked.
 > 301

Scegli qualsiasi opzione e premi Invio. Dovresti vedere il seguente output:

 How long (in seconds) do you want your redirects to be cached by visitors? [30]:
 > 

Scegli i valori predefiniti e premi Invio. Dovresti vedere il seguente output:

TRACKING
========

 Do you want track orphan visits? (visits to the base URL, invalid short URLs or other "not found" URLs) (yes/no) [yes]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

 Provide a parameter name that you will be able to use to disable tracking on specific request to short URLs (leave empty and this feature won't be enabled):
 > 

Basta premere Invio. Dovresti vedere il seguente output:

 Do you want to completely disable visits tracking? (yes/no) [no]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

 Do you want to disable tracking of visitors' IP addresses? (yes/no) [no]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

 Do you want visitors' remote IP addresses to be anonymized before persisting them to the database? (yes/no) [yes]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

 Do you want to disable tracking of visitors' "User Agents"? (yes/no) [no]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

 Do you want to disable tracking of visitors' "Referrers"? (yes/no) [no]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

REDIRECTS
=========

 Custom URL to redirect to when a user hits Shlink's base URL (If no value is provided, the user will see a default "404 not found" page):
 > http://shlink.linuxbuz.com

Fornisci il tuo nome di dominio e premi Invio. Dovresti vedere il seguente output:

 Custom URL to redirect to when a user hits an invalid short URL (If no value is provided, the user will see a default "404 not found" page):
 > http://shlink.linuxbuz.com

Fornisci il tuo nome di dominio e premi Invio. Dovresti vedere il seguente output:

 Custom URL to redirect to when a user hits a not found URL other than an invalid short URL (If no value is provided, the user will see a default "404 not found" page):
 > http://shlink.linuxbuz.com

Fornisci il tuo nome di dominio e premi Invio. Dovresti vedere il seguente output:

APPLICATION
===========

 Do you want to enable a safety check which will not allow short URLs to be deleted after receiving a specific amount of visits? (yes/no) [yes]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

 What is the amount of visits from which the system will not allow short URLs to be deleted? [15]:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

 What is the path from which shlink is going to be served? (Leave empty if you plan to serve shlink from the root of the domain) []:
 > 

Scegli l'opzione predefinita e premi Invio. Dovresti vedere il seguente output:

INTEGRATIONS
============

 Provide a comma-separated list of redis server URIs which will be used for shared caching purposes under shlink multi-instance contexts (Leave empty if you don't want to use redis cache):
 > 

 Custom configuration properly generated!

Initializing database... Success!
Updating database... Success!
Generating proxies... Success!
Downloading GeoLite2 db file... Success!

                                                                                                                        
 [OK] Installation complete!                                                                                                                                                            

Configura Nginx per Shlink

Successivamente, dovrai creare un file host virtuale Nginx per Shlink. Puoi crearlo con il seguente comando:

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

Aggiungi le seguenti righe:

server {
   listen 80;
   server_name shlink.example.com;

   root /var/www/html/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/php7.4-fpm.sock;
     fastcgi_index index.php;
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
     include fastcgi_params;
   }

}

Salva e chiudi il file, quindi verifica Nginx per eventuali errori con il seguente comando:

nginx -t

Dovresti ottenere il seguente output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Successivamente, riavvia il servizio Nginx per applicare le modifiche:

systemctl restart nginx

Puoi anche verificare lo stato di Nginx con il seguente comando:

systemctl status nginx

Dovresti ottenere il seguente output:

? nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2021-06-02 05:28:30 UTC; 4s ago
       Docs: man:nginx(8)
    Process: 25639 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 25653 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 25655 (nginx)
      Tasks: 2 (limit: 2353)
     Memory: 2.6M
     CGroup: /system.slice/nginx.service
             ??25655 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             ??25656 nginx: worker process

Jun 02 05:28:29 ubunt4 systemd[1]: Starting A high performance web server and a reverse proxy server...
Jun 02 05:28:30 ubunt4 systemd[1]: Started A high performance web server and a reverse proxy server.

Ora puoi installare il client Shlink configurato per abbreviare l'URL.

Puoi anche generare l'URL breve sul tuo server dalla riga di comando:

sudo -u www-data php7.4 /var/www/html/shlink/bin/cli short-url:generate

Per elencare tutti gli URL brevi, eseguire il seguente comando:

sudo -u www-data php7.4 /var/www/html/shlink/bin/cli short-url:list

Per visualizzare qualsiasi informazione della guida, eseguire il seguente comando:

sudo -u www-data php7.4 /var/www/html/shlink/bin/cli

Conclusione

Congratulazioni! hai installato correttamente Shlink URL shortener su Ubuntu 20.04. Ora puoi abbreviare l'URL utilizzando l'interfaccia CLI o il client basato sul Web.