UbuntuUbuntu Based

How To Install YOURLS on Ubuntu 24.04 LTS

Install YOURLS on Ubuntu 24.04

YOURLS (Your Own URL Shortener) represents the pinnacle of self-hosted URL shortening solutions, offering complete control over your data while providing robust analytics and customization options. Unlike third-party services such as bit.ly or tinyurl.com, YOURLS enables you to maintain full ownership of your shortened URLs, detailed statistics, and user data. This open-source PHP application delivers enterprise-grade features including custom domains, comprehensive analytics, plugin architecture, and API integration capabilities.

Ubuntu 24.04 LTS (Noble Numbat) provides the perfect foundation for hosting YOURLS, combining long-term support with enhanced security features and performance optimizations. The LTS designation ensures five years of security updates and maintenance, making it ideal for production deployments. This comprehensive guide walks you through every aspect of installing YOURLS on Ubuntu 24.04 LTS, from initial system preparation to advanced security hardening.

You’ll learn to configure a complete LAMP stack, optimize database performance, implement security best practices, and troubleshoot common installation issues. Whether you’re a system administrator, web developer, or business owner seeking URL shortening independence, this tutorial provides the expertise needed for a successful deployment.

Prerequisites and System Requirements

Hardware and Software Requirements

YOURLS operates efficiently on modest hardware configurations, making it accessible for various deployment scenarios. The minimum requirements include 1GB of RAM, 1 CPU core, and 10GB of storage space, though these specifications suit only light usage. For production environments handling substantial traffic, consider 2GB RAM, 2 CPU cores, and 20GB SSD storage for optimal performance.

VPS (Virtual Private Server) solutions often provide the best balance between cost and performance for YOURLS deployments. Cloud providers like DigitalOcean, Vultr, or Linode offer Ubuntu 24.04 LTS instances starting at $5-10 monthly, providing sufficient resources for most use cases. Dedicated servers become necessary only for high-traffic scenarios exceeding 100,000 URL shortenings monthly.

Ubuntu 24.04 LTS Specific Requirements

Fresh Ubuntu 24.04 LTS installations provide the cleanest foundation for YOURLS deployment, minimizing potential conflicts with existing software configurations. Ensure your system includes essential packages like curl, wget, git, and unzip for downloading and managing installation files. The installation process requires sudo privileges or root access for system-level modifications.

Network connectivity and DNS configuration play crucial roles in successful YOURLS deployment. Verify your server can access external repositories for package downloads and updates. Configure your domain’s DNS records to point to your server’s IP address before beginning the installation process.

Pre-installation Checklist

Domain name configuration requires careful attention to ensure proper YOURLS functionality. Create an A record pointing your chosen domain (e.g., short.yourdomain.com) to your server’s IP address. Allow 24-48 hours for DNS propagation, though changes often take effect within minutes.

SSH access configuration ensures secure server management throughout the installation process. Generate SSH key pairs for passwordless authentication and disable root password login for enhanced security. Configure your firewall to allow SSH connections on port 22 (or your custom SSH port) before proceeding with remote installation.

Installing the LAMP Stack Foundation

System Updates and Package Management

Begin every Ubuntu 24.04 LTS installation with comprehensive system updates to ensure access to the latest security patches and software versions. Execute the following commands to refresh package repositories and upgrade existing software:

sudo apt update && sudo apt upgrade -y
sudo apt install wget curl git unzip software-properties-common apt-transport-https ca-certificates gnupg lsb-release -y

These commands update the package database, upgrade installed packages, and install essential tools required for YOURLS installation. The -y flag automatically confirms package installations, streamlining the process for experienced administrators.

Apache Web Server Installation and Configuration

Apache 2.4+ provides robust web server capabilities perfectly suited for YOURLS hosting requirements. Ubuntu 24.04 LTS repositories include Apache 2.4.58 or newer, ensuring compatibility with modern web standards and security protocols:

sudo apt install apache2 -y
sudo systemctl enable apache2
sudo systemctl start apache2

Enable the mod_rewrite module, essential for YOURLS URL rewriting functionality. This module transforms user-friendly shortened URLs into their corresponding database queries:

sudo a2enmod rewrite
sudo a2enmod ssl
sudo a2enmod headers
sudo systemctl restart apache2

Configure basic Apache security settings by editing the main configuration file. Create a backup before making changes:

sudo cp /etc/apache2/apache2.conf /etc/apache2/apache2.conf.backup
sudo nano /etc/apache2/apache2.conf

Add security headers and disable unnecessary information disclosure by appending these directives:

ServerTokens Prod
ServerSignature Off
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"

MySQL/MariaDB Database Server Setup

MariaDB offers enhanced performance and security compared to traditional MySQL installations. Ubuntu 24.04 LTS includes MariaDB 10.11, providing excellent compatibility with YOURLS database requirements:

sudo apt install mariadb-server mariadb-client -y
sudo systemctl enable mariadb
sudo systemctl start mariadb

Secure your MariaDB installation using the built-in security script that removes test databases, anonymous users, and insecure default settings:

sudo mysql_secure_installation

Follow the interactive prompts, setting a strong root password and answering “Y” to all security questions. This process removes test databases, disables remote root access, and eliminates anonymous user accounts that could compromise system security.

PHP Installation and Configuration

PHP 8.x Installation for Ubuntu 24.04

Ubuntu 24.04 LTS includes PHP 8.4 by default, providing excellent performance improvements and security enhancements over previous versions. Install PHP and essential extensions required for YOURLS operation:

sudo apt install php php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-zip php-bcmath php-json -y

Verify PHP installation and extension availability using the command line interface:

php -v
php -m | grep -E "(curl|mysql|gd|mbstring)"

Consider PHP-FPM for improved performance in production environments. PHP-FPM (FastCGI Process Manager) offers better resource management and process isolation compared to mod_php:

sudo systemctl enable php8.4-fpm
sudo systemctl start php8.4-fpm

PHP Configuration Optimization

Optimize PHP settings specifically for YOURLS requirements by editing the PHP configuration file. Locate your PHP version’s configuration directory:

sudo nano /etc/php/8.4/apache2/php.ini

Adjust key performance and security parameters:

memory_limit = 256M
max_execution_time = 300
upload_max_filesize = 64M
post_max_size = 64M
max_input_vars = 3000
expose_php = Off
allow_url_fopen = On

These settings provide sufficient resources for YOURLS operation while maintaining security best practices. Restart Apache to apply configuration changes:

sudo systemctl restart apache2

Testing PHP Installation

Create a PHP information file to verify proper installation and module availability:

sudo nano /var/www/html/info.php

Add the following content:

<?php
phpinfo();
?>

Access the PHP info page through your web browser at http://your-server-ip/info.php. Verify that essential extensions (curl, mysql, gd, mbstring) appear in the loaded modules list. Remove this file immediately after verification for security purposes:

sudo rm /var/www/html/info.php

Database Configuration for YOURLS

Creating the YOURLS Database

Establish a dedicated database and user account for YOURLS to maintain security isolation and simplify permission management. Connect to MariaDB using the root account:

sudo mysql -u root -p

Execute the following SQL commands to create the database, user account, and assign appropriate privileges:

CREATE DATABASE yourlsdb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'yourlsuser'@'localhost' IDENTIFIED BY 'your_secure_password_here';
GRANT ALL PRIVILEGES ON yourlsdb.* TO 'yourlsuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Choose a strong password combining uppercase letters, lowercase letters, numbers, and special characters. Document these credentials securely, as you’ll need them during YOURLS configuration.

Database Optimization Settings

Configure MariaDB for optimal YOURLS performance by editing the main configuration file:

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Add performance optimization settings under the [mysqld] section:

[mysqld]
innodb_buffer_pool_size = 128M
innodb_log_file_size = 64M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
query_cache_type = 1
query_cache_size = 32M
max_connections = 100

Restart MariaDB to apply the new configuration:

sudo systemctl restart mariadb

These optimizations improve database query performance and reduce disk I/O operations, particularly beneficial for high-traffic YOURLS installations.

YOURLS Download and Installation

Downloading YOURLS Source Code

Download the latest stable YOURLS release from the official GitHub repository to ensure you receive the most recent security updates and features:

cd /tmp
wget https://github.com/YOURLS/YOURLS/archive/refs/heads/master.zip
unzip master.zip

Alternatively, clone the repository directly for easier future updates:

cd /var/www
sudo git clone https://github.com/YOURLS/YOURLS.git yourls

Verify download integrity by checking file permissions and directory structure:

ls -la yourls/

The directory should contain folders like admin, images, includes, user, and files such as yourls-api.php and yourls-loader.php.

File System Setup and Permissions

Configure proper ownership and permissions to ensure Apache can read YOURLS files while maintaining security:

sudo chown -R www-data:www-data /var/www/yourls
sudo chmod -R 755 /var/www/yourls
sudo chmod -R 644 /var/www/yourls/*.php

Set specific permissions for the user directory where configuration files reside:

sudo chmod 755 /var/www/yourls/user
sudo chmod 644 /var/www/yourls/user/*.php

Create necessary directories for logs and temporary files:

sudo mkdir -p /var/www/yourls/user/cache
sudo chown www-data:www-data /var/www/yourls/user/cache
sudo chmod 755 /var/www/yourls/user/cache

Configuration File Setup

Copy the sample configuration file and customize it for your installation:

cd /var/www/yourls/user
sudo cp config-sample.php config.php
sudo nano config.php

Configure essential database connection parameters:

define( 'YOURLS_DB_USER', 'yourlsuser' );
define( 'YOURLS_DB_PASS', 'your_secure_password_here' );
define( 'YOURLS_DB_NAME', 'yourlsdb' );
define( 'YOURLS_DB_HOST', 'localhost' );
define( 'YOURLS_DB_PREFIX', 'yourls_' );
define( 'YOURLS_SITE', 'https://short.yourdomain.com' );
define( 'YOURLS_HOURS_OFFSET', 0 );
define( 'YOURLS_LANG', '' );

Add administrative users for YOURLS management:

$yourls_user_passwords = array(
    'admin' => 'admin_password_here',
    'username2' => 'password2_here'
);

Generate a unique cookiekey for session security:

define( 'YOURLS_COOKIEKEY', 'insert_random_string_here' );

Web Server Configuration

Apache Virtual Host Configuration

Create a dedicated virtual host for your YOURLS installation to isolate it from other web applications and enable SSL/TLS configuration:

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

Configure the virtual host with appropriate security headers and URL rewriting rules:

<VirtualHost *:80>
    ServerName short.yourdomain.com
    DocumentRoot /var/www/yourls
    
    <Directory /var/www/yourls>
        AllowOverride All
        Require all granted
        Options -Indexes
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/yourls_error.log
    CustomLog ${APACHE_LOG_DIR}/yourls_access.log combined
    
    # Security headers
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
</VirtualHost>

Enable the virtual host and disable the default site:

sudo a2ensite yourls.conf
sudo a2dissite 000-default.conf
sudo systemctl reload apache2

Create or verify the .htaccess file in the YOURLS root directory for URL rewriting:

sudo nano /var/www/yourls/.htaccess

Add the following rewrite rules:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /yourls-loader.php [L]

Alternative: Nginx Configuration

For administrators preferring Nginx, configure a server block with similar functionality:

sudo nano /etc/nginx/sites-available/yourls
server {
    listen 80;
    server_name short.yourdomain.com;
    root /var/www/yourls;
    index index.php;
    
    location / {
        try_files $uri $uri/ /yourls-loader.php?$args;
    }
    
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
    
    location ~ /\.ht {
        deny all;
    }
}

YOURLS Installation and Setup

Running the Installation Wizard

Access the YOURLS installation interface by navigating to https://short.yourdomain.com/admin/ in your web browser. The installation wizard automatically detects your configuration and presents a clean interface for completing the setup process.

Follow the step-by-step installation procedure:

  1. Review system requirements – YOURLS validates PHP extensions and database connectivity
  2. Confirm configuration settings – Verify database parameters and site URL
  3. Initialize database tables – Allow YOURLS to create necessary database structure
  4. Complete installation – Receive confirmation of successful setup

Monitor the installation process for any error messages indicating configuration issues. Common problems include database connection failures, insufficient file permissions, or missing PHP extensions.

Install YOURLS on Ubuntu 24.04 LTS

Post-installation Verification

Test core YOURLS functionality by creating your first shortened URL through the administration interface. Enter a long URL in the provided field and verify that:

  • URL shortening completes successfully
  • Shortened URL redirects properly to the original destination
  • Click statistics appear in the administration dashboard
  • Database contains the new URL entry

Verify database connectivity and table creation by accessing your MariaDB instance:

mysql -u yourlsuser -p yourlsdb
SHOW TABLES;

Check log files for any warnings or errors that might indicate configuration problems:

sudo tail -f /var/log/apache2/yourls_error.log

Security Hardening and Best Practices

Server-level Security Measures

Configure UFW (Uncomplicated Firewall) to restrict network access to essential services only:

sudo ufw enable
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 'Apache Full'

Implement Fail2Ban protection against brute-force attacks targeting your YOURLS admin interface:

sudo apt install fail2ban -y
sudo nano /etc/fail2ban/jail.local

Configure custom jail rules for YOURLS protection:

[yourls]
enabled = true
port = http,https
filter = yourls
logpath = /var/log/apache2/yourls_access.log
maxretry = 5
bantime = 3600

Enable automatic security updates to maintain system security without manual intervention:

sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure -plow unattended-upgrades

YOURLS-specific Security

Strengthen administrative passwords using complex combinations of characters, numbers, and symbols. Consider implementing two-factor authentication through available YOURLS plugins for additional security layers.

Configure API access restrictions by limiting API usage to specific IP addresses or requiring authentication tokens:

define( 'YOURLS_PRIVATE', true );
define( 'YOURLS_PRIVATE_API', true );

Implement rate limiting to prevent abuse of your URL shortening service:

define( 'YOURLS_FLOOD_DELAY_SECONDS', 5 );
define( 'YOURLS_FLOOD_IP_DELAY_SECONDS', 60 );

SSL/TLS Certificate Installation

Install Let’s Encrypt certificates for free SSL/TLS encryption using Certbot:

sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d short.yourdomain.com

Configure automatic certificate renewal:

sudo crontab -e

Add the renewal command:

0 12 * * * /usr/bin/certbot renew --quiet

Verify SSL configuration using online tools like SSL Labs’ SSL Test to ensure proper implementation of security protocols.

Performance Optimization and Maintenance

Caching and Performance Tuning

Enable PHP OPcache for improved script execution performance:

sudo nano /etc/php/8.3/apache2/php.ini

Configure OPcache settings:

opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=2
opcache.fast_shutdown=1

Implement database query optimization by adding appropriate indexes to frequently accessed tables:

USE yourlsdb;
CREATE INDEX idx_keyword ON yourls_url(keyword);
CREATE INDEX idx_url ON yourls_url(url);
CREATE INDEX idx_timestamp ON yourls_url(timestamp);

Configure Apache MPM settings for optimal resource utilization:

sudo nano /etc/apache2/mods-enabled/mpm_prefork.conf

Regular Maintenance Tasks

Establish automated backup procedures for both YOURLS files and database content:

#!/bin/bash
# Daily backup script
tar -czf /backups/yourls-$(date +%Y%m%d).tar.gz /var/www/yourls
mysqldump -u yourlsuser -p yourlsdb > /backups/yourls-db-$(date +%Y%m%d).sql

Schedule regular security updates and system maintenance:

sudo crontab -e

Add maintenance commands:

0 2 * * 0 apt update && apt upgrade -y
0 3 * * 0 /path/to/backup-script.sh

Monitor system performance using tools like htop, iotop, and netstat to identify potential bottlenecks or resource constraints.

Troubleshooting Common Issues

Installation Problems and Solutions

Database connection errors typically result from incorrect credentials or server configuration. Verify database parameters in config.php and test connectivity:

mysql -u yourlsuser -p yourlsdb -e "SELECT 1"

PHP extension missing issues prevent YOURLS from functioning properly. Verify required extensions:

php -m | grep -E "(curl|mysql|gd|mbstring|json)"

Permission problems manifest as file access errors or installation failures. Reset permissions using:

sudo chown -R www-data:www-data /var/www/yourls
sudo chmod -R 755 /var/www/yourls

Runtime Issues and Fixes

URL shortening failures often indicate .htaccess or rewrite rule problems. Verify mod_rewrite is enabled and .htaccess contains proper directives.

Admin panel access problems may result from authentication issues or session configuration. Enable debugging mode by adding to config.php:

define( 'YOURLS_DEBUG', true );

Performance degradation typically stems from database optimization needs or insufficient server resources. Monitor system metrics and optimize database queries as needed.

Congratulations! You have successfully installed YOURLS. Thanks for using this tutorial for installing YOURLS (Your Own URL Shortener) on Ubuntu 24.04 LTS system. For additional help or useful information, we recommend you check the official YOURLS website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button