GNU/Linux >> Tutoriales Linux >  >> Ubuntu

Cómo instalar el acortador de URL Shlink con Nginx en Ubuntu 20.04

Shlink es un acortador de URL de código abierto y autohospedado escrito en PHP. Se utiliza para generar y gestionar URL cortas desde la línea de comandos. Le permite realizar un seguimiento de todas las visitas de sus URL cortas, incluida la ubicación, el navegador o la referencia. Se puede integrar con herramientas de terceros mediante la API de Shlink. Proporciona una interfaz de línea de comandos para acortar URL.

En este tutorial, le mostraré cómo instalar Shlink en Ubuntu 20.04.

Requisitos

  • Un servidor con Ubuntu 20.04.
  • Un nombre de dominio válido apuntado con la IP de su servidor.
  • Se configura una contraseña raíz en el servidor.

Cómo empezar

Primero, actualice los paquetes del sistema a la versión actualizada ejecutando el siguiente comando:

apt-get update -y

Una vez que todos los paquetes estén actualizados, puede continuar con el siguiente paso.

Instalar servidor LEMP

Primero, instale Nginx, PHP, MariaDB y otros paquetes requeridos con el siguiente 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 vez que todos los paquetes estén instalados, puede continuar con el siguiente paso.

Shlink usa MariaDB como base de datos. Por lo tanto, deberá crear una base de datos y un usuario para Shlink. Primero, conéctese a MariaDB con el siguiente comando:

mysql

Una vez conectado, cree una base de datos y un usuario con el siguiente comando:

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

A continuación, elimine los privilegios y salga de MariaDB con el siguiente comando:

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

Primero, descargue la última versión de Shlink desde su página de descarga oficial:

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

Una vez completada la descarga, descomprima el archivo descargado con el siguiente comando:

unzip shlink2.7.1_php7.4_dist.zip

A continuación, mueva el directorio extraído al directorio raíz web de Nginx:

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

A continuación, establezca el permiso y la propiedad adecuados con el siguiente comando:

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

A continuación, ejecute el siguiente comando para iniciar la instalación:

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

Se le pedirá que seleccione la base de datos como se muestra a continuación:

 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

Elija cualquier opción y presione Entrar. Se le pedirá que proporcione el nombre de la base de datos como se muestra a continuación:

 Database name [shlink]:
 > 

Proporcione el nombre de su base de datos o presione Entrar para elegir el predeterminado. Se le pedirá que proporcione el host de la base de datos:

 Database host [localhost]:
 > 

Proporcione el host de su base de datos o presione Enter para elegir el valor predeterminado. Se le pedirá que proporcione el puerto de la base de datos:

 Database port [3306]:
 > 

Proporcione el puerto de su base de datos o presione Enter para elegir el predeterminado. Se le pedirá que proporcione el nombre de usuario de su base de datos:

 Database username:
 > shlink

Proporcione el nombre de usuario de su base de datos y presione Enter. Se le pedirá que proporcione su contraseña de usuario de la base de datos:

 Database password:
 > password

Proporcione su contraseña de usuario de la base de datos y presione Enter. Se le pedirá que proporcione un socket Unix.

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

Déjalo vacío y presiona Enter. Se le pedirá que proporcione el nombre de dominio:

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

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

Proporcione su nombre de dominio y presione Entrar. Se le pedirá que seleccione el Esquema:

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

Seleccione una opción y presione Entrar. Se le pedirá que valide las URL largas:

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

Elija la opción predeterminada y presione Entrar. Se le pedirá que proporcione la longitud de los códigos abreviados generados:

 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]:
 > 

Elija el valor predeterminado y presione Entrar. Debería ver el siguiente resultado:

 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]:
 > 

Seleccione la respuesta predeterminada y presione Entrar. Debería ver el siguiente resultado:

 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):
 > 

Déjalo vacío y presiona Enter. Debería ver el siguiente resultado:

 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

Elija cualquier opción y presione Entrar. Debería ver el siguiente resultado:

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

Elija los valores predeterminados y presione Entrar. Debería ver el siguiente resultado:

TRACKING
========

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

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

 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):
 > 

Simplemente presione Entrar. Debería ver el siguiente resultado:

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

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

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

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

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

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

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

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

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

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

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

Proporcione su nombre de dominio y presione Entrar. Debería ver el siguiente resultado:

 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

Proporcione su nombre de dominio y presione Entrar. Debería ver el siguiente resultado:

 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

Proporcione su nombre de dominio y presione Entrar. Debería ver el siguiente resultado:

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]:
 > 

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

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

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

 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) []:
 > 

Elija la opción predeterminada y presione Entrar. Debería ver el siguiente resultado:

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!                                                                                                                                                            

A continuación, deberá crear un archivo de host virtual Nginx para Shlink. Puedes crearlo con el siguiente comando:

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

Agregue las siguientes líneas:

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;
   }

}

Guarde y cierre el archivo, luego verifique el Nginx por cualquier error con el siguiente comando:

nginx -t

Deberías obtener el siguiente resultado:

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

A continuación, reinicie el servicio Nginx para aplicar los cambios:

systemctl restart nginx

También puede verificar el estado de Nginx con el siguiente comando:

systemctl status nginx

Deberías obtener el siguiente resultado:

? 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 ubuntu2004 systemd[1]: Starting A high performance web server and a reverse proxy server...
Jun 02 05:28:30 ubuntu2004 systemd[1]: Started A high performance web server and a reverse proxy server.

Ahora puede instalar y configurar el cliente Shlink para acortar la URL.

También puede generar la URL corta en su servidor desde la línea de comando:

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

Para enumerar todas las URL cortas, ejecute el siguiente comando:

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

Para mostrar cualquier información de ayuda, ejecute el siguiente comando:

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

Conclusión

¡Felicidades! Ha instalado con éxito el acortador de URL Shlink en Ubuntu 20.04. Ahora puede acortar la URL utilizando la interfaz CLI o el cliente basado en web.


Ubuntu
  1. Cómo instalar WordPress con Nginx en Ubuntu 18.04

  2. Cómo instalar phpMyAdmin con Nginx en Ubuntu 18.04

  3. Cómo instalar MediaWiki con Nginx en Ubuntu 16.04

  4. Cómo instalar Grav CMS con Nginx en Ubuntu 16.04

  5. Cómo instalar SuiteCRM con Nginx en Ubuntu 16.04

Cómo instalar el acortador de URL Shlink en el servidor Ubuntu 20.04

Cómo instalar el acortador de URL Shlink en el servidor Ubuntu 18.04

Cómo instalar phpMyAdmin con Nginx (LEMP) en Ubuntu 20.04 LTS

Cómo instalar Nextcloud 13 en Ubuntu 16.04 con Nginx

Cómo instalar el acortador de URL Shlink con Nginx en Ubuntu 20.04

Cómo instalar WordPress con Nginx en Ubuntu 20.04