AlmaLinuxRHEL Based

How To Install Laravel on AlmaLinux 10

Install Laravel on AlmaLinux 10

Laravel stands as one of the most popular PHP frameworks for web development, offering elegant syntax and powerful features that streamline application development. When paired with AlmaLinux 10, a robust enterprise-grade Linux distribution, developers gain access to a stable, secure platform ideal for hosting modern web applications.

This comprehensive guide will walk you through installing Laravel on AlmaLinux 10, covering everything from initial system setup to security hardening. Whether you’re a seasoned system administrator or a developer venturing into server management, this tutorial provides detailed instructions to get your Laravel development environment running smoothly.

AlmaLinux 10 offers several advantages for Laravel hosting, including long-term support, enterprise-level security, and excellent compatibility with modern PHP versions. The combination creates an ideal foundation for both development and production Laravel applications.

You’ll learn to configure Apache web server, install PHP 8.4 with necessary extensions, set up MariaDB database, and implement security best practices. The entire process typically takes 15-20 minutes on a fresh AlmaLinux 10 installation.

Table of Contents

Prerequisites and System Requirements

Before beginning the Laravel installation process, ensure your system meets the necessary requirements for optimal performance and compatibility.

Hardware Requirements

Your AlmaLinux 10 server should have at least 4GB of RAM for smooth Laravel operation, though 8GB is recommended for production environments. Ensure adequate storage space with minimum 20GB available disk space for the operating system, web server, database, and Laravel application files.

A stable internet connection is essential for downloading packages and dependencies throughout the installation process.

Software Prerequisites

This guide assumes you have a fresh AlmaLinux 10 server installation with root or sudo access. You’ll need basic familiarity with Linux command-line operations, though we’ll explain each step thoroughly.

Ensure you have SSH access to your server and a valid domain name or IP address configured for web access. If you’re setting up a development environment, you can use the server’s IP address directly.

User Permissions and Access

Verify you can execute commands with sudo privileges by running:

sudo whoami

This should return “root” if your permissions are configured correctly.

Consider SELinux implications, as AlmaLinux 10 runs with SELinux enabled by default. We’ll address SELinux configuration during the setup process to ensure Laravel functions properly while maintaining security.

System Preparation and Updates

Proper system preparation ensures a clean foundation for your Laravel installation and prevents compatibility issues down the road.

Updating AlmaLinux 10 System

Start by updating all system packages to their latest versions. This ensures you have the most recent security patches and bug fixes:

sudo dnf update -y

The update process may take several minutes depending on your internet connection and the number of available updates. Once completed, consider rebooting the system if kernel updates were installed:

sudo reboot

Enabling Required Repositories

Laravel requires PHP 8.2 or higher, and AlmaLinux 10’s default repositories may not include the latest PHP versions. Enable the EPEL and Remi repositories to access current PHP packages:

sudo dnf install epel-release -y
sudo dnf install -y https://rpms.remirepo.net/enterprise/remi-release-10.rpm

Verify the repositories are enabled:

sudo dnf repolist | grep -E "(epel|remi)"

Firewall Configuration

Configure the firewall to allow HTTP and HTTPS traffic for web access:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Check firewall status to confirm the rules are active:

sudo firewall-cmd --list-services

SELinux Considerations

While keeping SELinux enabled is recommended for security, you may need to configure it properly for web applications. Check current SELinux status:

sestatus

For development environments, you might temporarily set SELinux to permissive mode, though this isn’t recommended for production:

sudo setenforce 0

Installing Web Server and PHP Dependencies

The web server and PHP installation form the foundation of your Laravel hosting environment. AlmaLinux 10 pairs excellently with Apache and PHP 8.4 for optimal Laravel performance.

Installing Apache Web Server

Apache HTTP Server provides reliable, feature-rich web hosting capabilities. Install Apache using DNF package manager:

sudo dnf install httpd -y

Start Apache service and enable it to start automatically on boot:

sudo systemctl start httpd
sudo systemctl enable httpd

Verify Apache is running correctly:

sudo systemctl status httpd

Test Apache functionality by visiting your server’s IP address in a web browser. You should see the default Apache welcome page.

Installing PHP 8.4 with Required Extensions

Laravel requires specific PHP extensions for full functionality. Enable PHP 8.4 from the Remi repository:

sudo dnf module enable php:remi-8.4 -y

Install PHP and essential extensions for Laravel:

sudo dnf install -y php php-cli php-common php-fpm php-mysqlnd php-opcache php-xml php-mbstring php-curl php-gd php-json php-zip php-bcmath php-tokenizer php-openssl php-pdo

Each extension serves specific Laravel functions:

  • php-mysqlnd: Database connectivity for MySQL/MariaDB
  • php-opcache: Performance optimization through bytecode caching
  • php-xml: XML processing capabilities
  • php-mbstring: Multi-byte string handling
  • php-curl: HTTP request functionality
  • php-gd: Image manipulation features
  • php-json: JSON data processing
  • php-zip: Archive handling for Composer
  • php-bcmath: Arbitrary precision mathematics
  • php-tokenizer: PHP code parsing
  • php-openssl: Encryption and security features
  • php-pdo: Database abstraction layer

Configuring PHP for Laravel

Optimize PHP configuration for Laravel applications by editing the main PHP configuration file:

sudo nano /etc/php.ini

Adjust these key settings for better Laravel performance:

memory_limit = 256M
upload_max_filesize = 100M
post_max_size = 100M
max_execution_time = 300
max_input_vars = 3000
date.timezone = "UTC"

Starting and Enabling Services

Ensure Apache and PHP-FPM services are running and configured to start on boot:

sudo systemctl start php-fpm
sudo systemctl enable php-fpm
sudo systemctl restart httpd

Verify PHP installation by creating a test file:

echo "" | sudo tee /var/www/html/phpinfo.php

Visit http://your-server-ip/phpinfo.php to confirm PHP is working correctly. Remove this file after testing for security:

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

Installing Composer

Composer is the dependency manager for PHP and essential for Laravel project management. Installing Composer correctly ensures smooth package management throughout your Laravel development process.

Downloading Composer Installer

Download the official Composer installer using PHP. This method ensures you get the authentic, unmodified installer:

cd /tmp
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

Verifying Installation Integrity

Security-conscious installation requires verifying the installer’s integrity. Download the expected SHA-384 hash:

EXPECTED_SIGNATURE="$(php -r 'copy("https://composer.github.io/installer.sig", "php://stdout");')"

Verify the downloaded installer matches the expected signature:

ACTUAL_SIGNATURE="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"

Compare signatures and proceed only if they match:

if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ]; then
    echo 'ERROR: Invalid installer signature'
    rm composer-setup.php
    exit 1
fi

Global Composer Installation

Install Composer globally for system-wide access:

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

Clean up the installer file:

rm composer-setup.php

Verify Composer installation:

composer --version

The output should display Composer version information, confirming successful installation.

Setting Up Composer Directories

Create necessary directories for Apache user to access Composer:

sudo mkdir -p /usr/share/httpd/.composer/{cache,config}
sudo chown -R apache:apache /usr/share/httpd/.composer

Database Setup and Configuration

Laravel applications typically require a database backend. MariaDB provides excellent MySQL compatibility with enhanced performance and features, making it ideal for Laravel applications.

Installing MariaDB Server

Install MariaDB server and client packages:

sudo dnf install mariadb-server mariadb -y

Start MariaDB service and enable automatic startup:

sudo systemctl start mariadb
sudo systemctl enable mariadb

Verify MariaDB is running:

sudo systemctl status mariadb

Securing Database Installation

Run the security script to improve MariaDB security:

sudo mysql_secure_installation

The script will prompt for several security settings:

  • Set root password: Choose a strong password
  • Remove anonymous users: Select ‘Y’ for security
  • Disallow root login remotely: Select ‘Y’ for security
  • Remove test database: Select ‘Y’ to clean up
  • Reload privilege tables: Select ‘Y’ to apply changes

Creating Laravel Database and User

Connect to MariaDB as root:

sudo mysql -u root -p

Create a dedicated database for your Laravel application:

CREATE DATABASE laravel_app CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Create a dedicated user with appropriate privileges:

CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON laravel_app.* TO 'laravel_user'@'localhost';
FLUSH PRIVILEGES;

Exit MariaDB:

EXIT;

Configuring Database Connection

Test the new database connection:

mysql -u laravel_user -p laravel_app

If successful, you’ll see the MariaDB prompt. Exit with EXIT; command.

Consider optimizing MariaDB configuration for Laravel workloads by editing /etc/my.cnf.d/server.cnf:

[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 200
query_cache_type = 1
query_cache_size = 64M

Restart MariaDB to apply configuration changes:

sudo systemctl restart mariadb

Creating Laravel Project

With all dependencies installed, you’re ready to create your Laravel application. This process involves setting up proper directory structure and permissions for web server access.

Setting Up Project Directory

Create the project directory within Apache’s document root:

sudo mkdir -p /var/www/laravelapp

Set proper ownership for Apache to manage the files:

sudo chown -R apache:apache /var/www/laravelapp

Create Composer cache directories for the Apache user:

sudo mkdir -p /usr/share/httpd/.composer/{cache,config}
sudo chown -R apache:apache /usr/share/httpd/.composer

Installing Laravel via Composer

Navigate to the project directory:

cd /var/www/laravelapp

Create a new Laravel project using Composer, running as the Apache user:

sudo -u apache composer create-project laravel/laravel .

This command downloads the latest Laravel version and installs all dependencies. The process may take several minutes depending on your internet connection.

Directory Permissions Configuration

Laravel requires specific directories to be writable by the web server. Set appropriate permissions:

sudo chmod -R 775 /var/www/laravelapp/storage
sudo chmod -R 775 /var/www/laravelapp/bootstrap/cache

Ensure Apache maintains ownership:

sudo chown -R apache:apache /var/www/laravelapp

For enhanced security, you can be more restrictive with permissions:

sudo find /var/www/laravelapp -type f -exec chmod 644 {} \;
sudo find /var/www/laravelapp -type d -exec chmod 755 {} \;
sudo chmod -R 775 /var/www/laravelapp/storage
sudo chmod -R 775 /var/www/laravelapp/bootstrap/cache

Verifying Laravel Installation

Check that Laravel files are properly installed:

ls -la /var/www/laravelapp

You should see typical Laravel directories including app, config, database, public, resources, routes, storage, and vendor.

Verify Composer dependencies are installed:

sudo -u apache composer --working-dir=/var/www/laravelapp show

Web Server Configuration

Proper Apache configuration ensures Laravel applications run efficiently with clean URLs and appropriate security settings.

Creating Apache Virtual Host

Create a new virtual host configuration file for your Laravel application:

sudo nano /etc/httpd/conf.d/laravel.conf

Add the following configuration, replacing yourdomain.com with your actual domain:

<VirtualHost *:80>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com
    DocumentRoot /var/www/laravelapp/public
    
    <Directory /var/www/laravelapp/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    <Directory /var/www/laravelapp>
        Options -Indexes
        AllowOverride None
        Require all denied
    </Directory>
    
    ErrorLog /var/log/httpd/laravel-error.log
    CustomLog /var/log/httpd/laravel-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"
</VirtualHost>

Configuring Document Root

The virtual host configuration points to Laravel’s public directory, which contains the index.php file and should be the only directory accessible to web visitors. This setup enhances security by keeping Laravel’s core files outside the web-accessible directory.

Enabling URL Rewriting

Enable Apache’s rewrite module for Laravel’s pretty URLs:

sudo dnf install httpd-tools -y

The mod_rewrite module should be enabled by default in AlmaLinux 10’s Apache installation. Verify it’s loaded:

sudo httpd -M | grep rewrite

Testing Apache Configuration

Before restarting Apache, test the configuration syntax:

sudo httpd -t

A “Syntax OK” message confirms your configuration is valid. If errors appear, review your virtual host configuration for typos.

Restart Apache to apply the new configuration:

sudo systemctl restart httpd

SSL Configuration (Optional)

For production environments, implement SSL/TLS encryption. Install Certbot for Let’s Encrypt certificates:

sudo dnf install python3-certbot-apache -y

Obtain SSL certificate:

sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

Certbot automatically configures Apache for HTTPS and sets up automatic certificate renewal.

Setting Up Log Rotation

Configure log rotation for Laravel-specific logs:

sudo nano /etc/logrotate.d/laravel

Add the following configuration:

/var/log/httpd/laravel-*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 apache apache
    postrotate
        /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
    endscript
}

Environment Configuration

Laravel’s environment configuration controls application behavior, database connections, and various settings. Proper configuration ensures your application runs securely and efficiently.

Configuring Laravel .env File

Navigate to your Laravel project directory and copy the environment example file:

cd /var/www/laravelapp
sudo -u apache cp .env.example .env

Edit the environment file:

sudo -u apache nano .env

Setting Application Key

Generate a unique application key for security:

sudo -u apache php artisan key:generate

This command automatically updates the APP_KEY value in your .env file. The application key is crucial for encrypting user sessions and other encrypted data.

Database Connection Setup

Configure database connection parameters in the .env file:

APP_NAME="Laravel Application"
APP_ENV=production
APP_KEY=base64:your-generated-key-here
APP_DEBUG=false
APP_URL=http://yourdomain.com

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=error

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=laravel_user
DB_PASSWORD=your_secure_password

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

Environment-Specific Settings

Adjust settings based on your environment:

For Production:

  • Set APP_ENV=production
  • Set APP_DEBUG=false
  • Configure proper logging levels
  • Use secure session and cache drivers

For Development:

  • Set APP_ENV=local
  • Set APP_DEBUG=true
  • Enable detailed error reporting

Mail Configuration

If your Laravel application sends emails, configure mail settings:

MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

Cache Configuration

For improved performance, consider configuring Redis or Memcached for caching:

sudo dnf install redis -y
sudo systemctl start redis
sudo systemctl enable redis

Update .env for Redis caching:

CACHE_DRIVER=redis
SESSION_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Securing Environment Files

Protect the .env file from web access:

sudo chmod 600 /var/www/laravelapp/.env
sudo chown apache:apache /var/www/laravelapp/.env

Database Migration and Testing

Laravel includes database migrations that create essential application tables. Running migrations and testing ensures your installation is complete and functional.

Running Initial Migrations

Clear configuration cache to ensure fresh settings are loaded:

sudo -u apache php artisan config:clear
sudo -u apache php artisan cache:clear

Run Laravel’s default migrations:

cd /var/www/laravelapp
sudo -u apache php artisan migrate

The migration process creates tables for user authentication, password resets, and other Laravel features. Answer “Yes” when prompted to confirm migration in production.

Testing Database Connection

Verify database connectivity using Laravel’s tinker command:

sudo -u apache php artisan tinker

Test a simple database query:

DB::connection()->getPdo();

Exit tinker with exit command.

Verifying Installation

Test your Laravel application by visiting your domain in a web browser. You should see Laravel’s welcome page with version information and helpful links.

Alternatively, use Laravel’s built-in development server for testing:

sudo -u apache php artisan serve --host=0.0.0.0 --port=8000

Visit http://your-server-ip:8000 to access the application.

Running Database Seeders

If you want sample data for testing, run Laravel’s database seeders:

sudo -u apache php artisan db:seed

Optimizing for Production

For production environments, optimize Laravel’s performance:

sudo -u apache php artisan config:cache
sudo -u apache php artisan route:cache
sudo -u apache php artisan view:cache

These commands cache configuration, routes, and views for improved performance.

Security Hardening and Best Practices

Implementing security best practices protects your Laravel application from common vulnerabilities and ensures robust operation in production environments.

File Permission Security

Implement strict file permissions for enhanced security:

# Set ownership to Apache user
sudo chown -R apache:apache /var/www/laravelapp

# Restrict directory permissions
sudo find /var/www/laravelapp -type d -exec chmod 755 {} \;

# Restrict file permissions
sudo find /var/www/laravelapp -type f -exec chmod 644 {} \;

# Make writable directories
sudo chmod -R 775 /var/www/laravelapp/storage
sudo chmod -R 775 /var/www/laravelapp/bootstrap/cache

# Secure sensitive files
sudo chmod 600 /var/www/laravelapp/.env

SELinux Configuration

Configure SELinux contexts for web applications:

sudo setsebool -P httpd_can_network_connect 1
sudo setsebool -P httpd_can_network_connect_db 1
sudo semanage fcontext -a -t httpd_exec_t "/var/www/laravelapp/public(/.*)?\.php"
sudo restorecon -R /var/www/laravelapp

Set appropriate SELinux contexts:

sudo chcon -R -t httpd_exec_t /var/www/laravelapp/public
sudo chcon -R -t httpd_rw_content_t /var/www/laravelapp/storage
sudo chcon -R -t httpd_rw_content_t /var/www/laravelapp/bootstrap/cache

Application Security Settings

Configure Laravel security features in config/app.php:

'debug' => env('APP_DEBUG', false),
'url' => env('APP_URL', 'https://yourdomain.com'),
'asset_url' => env('ASSET_URL', null),
'timezone' => 'UTC',
'locale' => 'en',
'fallback_locale' => 'en',
'faker_locale' => 'en_US',
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',

Monitoring and Maintenance

Set up log monitoring for security events:

sudo nano /etc/logrotate.d/laravel-app

Configure log rotation:

/var/www/laravelapp/storage/logs/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 644 apache apache
}

Regular Update Procedures

Create a maintenance script for regular updates:

sudo nano /usr/local/bin/laravel-update.sh

Add update commands:

#!/bin/bash
cd /var/www/laravelapp
sudo -u apache composer update
sudo -u apache php artisan migrate --force
sudo -u apache php artisan config:cache
sudo -u apache php artisan route:cache
sudo -u apache php artisan view:cache
sudo systemctl reload httpd

Make the script executable:

sudo chmod +x /usr/local/bin/laravel-update.sh

Backup Strategies

Implement automated backups for your Laravel application and database:

sudo nano /usr/local/bin/laravel-backup.sh

Create backup script:

#!/bin/bash
BACKUP_DIR="/backup/laravel/$(date +%Y%m%d)"
mkdir -p $BACKUP_DIR

# Backup files
tar -czf $BACKUP_DIR/laravel-files.tar.gz -C /var/www laravelapp

# Backup database
mysqldump -u laravel_user -p'your_password' laravel_app > $BACKUP_DIR/database.sql

# Keep only last 7 days
find /backup/laravel -type d -mtime +7 -exec rm -rf {} +

Troubleshooting Common Issues

Understanding common Laravel installation issues and their solutions helps maintain a stable development environment and quickly resolve problems.

Permission-Related Errors

Issue: “Permission denied” errors when accessing Laravel application.

Solution: Verify file permissions and ownership:

sudo chown -R apache:apache /var/www/laravelapp
sudo chmod -R 775 /var/www/laravelapp/storage
sudo chmod -R 775 /var/www/laravelapp/bootstrap/cache

Issue: SELinux blocking web access.

Solution: Configure SELinux contexts:

sudo setsebool -P httpd_can_network_connect 1
sudo restorecon -R /var/www/laravelapp

Database Connection Issues

Issue: “Connection refused” database errors.

Solution: Verify MariaDB service status:

sudo systemctl status mariadb
sudo systemctl start mariadb

Check database credentials in .env file and test connection manually:

mysql -u laravel_user -p laravel_app

Apache Configuration Problems

Issue: 404 errors or server not responding.

Solution: Test Apache configuration:

sudo httpd -t
sudo systemctl status httpd

Verify virtual host configuration and restart Apache:

sudo systemctl restart httpd

PHP Extension Missing Errors

Issue: Laravel reports missing PHP extensions.

Solution: Install required extensions:

sudo dnf install php-extension-name -y
sudo systemctl restart httpd

Common missing extensions:

  • php-mbstring for string handling
  • php-xml for XML processing
  • php-curl for HTTP requests
  • php-zip for archive handling

Check installed extensions:

php -m | grep extension-name

Composer Issues

Issue: Composer memory limit errors.

Solution: Increase PHP memory limit:

sudo php -d memory_limit=2G /usr/local/bin/composer install

Issue: Composer dependency conflicts.

Solution: Clear Composer cache and reinstall:

sudo -u apache composer clear-cache
sudo -u apache composer install --no-cache

Performance Optimization

Issue: Slow application response times.

Solution: Enable PHP OPcache and configure caching:

sudo nano /etc/php.d/10-opcache.ini

Optimize OPcache settings:

opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=7963
opcache.revalidate_freq=5

Clear and rebuild Laravel caches:

sudo -u apache php artisan optimize:clear
sudo -u apache php artisan optimize

Congratulations! You have successfully installed Laravel. Thanks for using this tutorial for installing the Laravel PHP Framework on your AlmaLinux OS 10 system. For additional help or useful information, we recommend you check the official Laravel 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