RHEL BasedRocky Linux

How To Install CodeIgniter on Rocky Linux 10

Install CodeIgniter on Rocky Linux 10

CodeIgniter stands as one of the most popular PHP frameworks for building dynamic web applications with speed and efficiency. Rocky Linux 10, a community-driven enterprise operating system, provides the perfect foundation for hosting modern web applications with enterprise-grade stability and security. This comprehensive guide walks through the complete process of installing CodeIgniter 4 on Rocky Linux 10, from initial system preparation to deployment-ready configuration. Whether you’re developing a lightweight content management system, a RESTful API, or a full-featured web application, this tutorial equips you with the knowledge to set up a robust development environment.

Prerequisites and System Requirements

Before beginning the installation process, ensure your environment meets the necessary requirements. Rocky Linux 10 requires a server or virtual machine with minimum specifications to run smoothly.

Hardware and Software Prerequisites

A properly configured Rocky Linux 10 server forms the foundation of this installation. The system should have at least 1GB of RAM, though 2GB or more is recommended for optimal performance. Allocate at least 2GB of free disk space to accommodate the operating system, web server, database, and framework files. Root or sudo privileges are essential for installing packages and configuring services. An active internet connection enables package downloads from official repositories, and SSH access allows remote server management.

Required Software Components

CodeIgniter 4 requires PHP version 8.1 or newer to function properly. The latest CodeIgniter 4.6.x series performs best with PHP 8.3 or higher, taking advantage of modern language features and performance improvements. Apache or Nginx serves as the web server, with Apache being the focus of this guide due to its widespread adoption and straightforward configuration. MariaDB 10.3 or newer, or MySQL 5.1 and above, provides database functionality. Composer, the PHP dependency manager, simplifies framework installation and manages project dependencies. Critical PHP extensions include intl, mbstring, php-json, php-mysqlnd, php-xml, and curl to ensure full framework compatibility.

Step 1: Update Rocky Linux 10 System

Keeping your Rocky Linux 10 system updated ensures security patches and bug fixes are applied. This foundational step prevents compatibility issues during software installation.

Open your terminal and execute the system update command:

sudo dnf update -y

The DNF package manager, Rocky Linux’s default package management tool, checks repositories for available updates and installs them automatically. The -y flag confirms all prompts automatically, streamlining the update process. If kernel updates are installed, reboot the system to apply changes:

sudo reboot

After the system restarts, verify the update completed successfully by checking the system version and available packages. This preparation ensures all subsequent installations proceed smoothly.

Step 2: Install Apache Web Server

Apache HTTP Server powers millions of websites worldwide and integrates seamlessly with PHP applications. Rocky Linux 10 includes Apache in its official repositories, simplifying installation.

Installing Apache

Install the Apache web server and its tools using DNF:

sudo dnf install httpd httpd-tools -y

The httpd package contains the Apache server, while httpd-tools provides utilities for server management and testing. Start the Apache service immediately:

sudo systemctl start httpd

Enable Apache to start automatically on system boot:

sudo systemctl enable httpd

This configuration ensures continuous service availability after server restarts. Verify Apache is running correctly:

sudo systemctl status httpd

A green “active (running)” status indicates successful installation and startup.

Configuring Firewall

Rocky Linux 10’s firewall blocks incoming web traffic by default for security purposes. Open the necessary ports to allow HTTP and HTTPS connections:

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

The --permanent flag ensures rules persist after system reboots. The reload command applies changes immediately without disrupting existing connections. Verify firewall configuration:

sudo firewall-cmd --list-all

HTTP and HTTPS services should appear in the allowed services list.

Testing Apache Installation

Create a simple test file to confirm Apache serves content correctly. Navigate to the web root directory:

cd /var/www/html
sudo nano index.html

Add basic HTML content, save the file, and access your server’s IP address through a web browser. The default Apache welcome page or your custom HTML should display, confirming proper installation and configuration.

Step 3: Install MariaDB Database Server

Database functionality is essential for dynamic web applications. MariaDB, a community-developed fork of MySQL, offers excellent performance and reliability.

Installing MariaDB

Install MariaDB server and client packages:

sudo dnf install mariadb-server mariadb -y

Start the MariaDB service:

sudo systemctl start mariadb

Enable MariaDB to start on boot:

sudo systemctl enable mariadb

Check the service status to ensure proper operation:

sudo systemctl status mariadb

Securing MariaDB Installation

MariaDB includes a security script that removes default insecure settings. Run the security configuration wizard:

sudo mysql_secure_installation

The script prompts for several security configurations. Set a strong root password when prompted. Remove anonymous user accounts that allow unauthorized access. Disable remote root login to prevent external attacks on the privileged account. Remove the test database that serves no production purpose. Reload privilege tables to apply changes immediately. These steps significantly enhance database security and should never be skipped in production environments.

Step 4: Install PHP 8.3 and Required Extensions

PHP serves as the foundation for CodeIgniter. Rocky Linux 10 includes PHP in its repositories, but accessing the latest PHP 8.3 version requires additional repository configuration.

Enabling Required Repositories

Enable the CodeReady Builder (CRB) repository for additional development packages:

sudo dnf config-manager --set-enabled crb

Install the EPEL (Extra Packages for Enterprise Linux) repository:

sudo dnf install epel-release -y

EPEL provides packages not included in Rocky Linux’s default repositories. Add the Remi repository for the latest PHP versions:

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

Installing PHP 8.3

Switch to the PHP 8.3 module stream:

sudo dnf module reset php
sudo dnf module enable php:remi-8.3

Install PHP and all CodeIgniter-required extensions:

sudo dnf install php php-cli php-mysqlnd php-mbstring php-gd php-curl php-zip php-intl php-json php-xml php-opcache php-common -y

These extensions provide functionality for database connections, string manipulation, internationalization, JSON handling, XML processing, and performance optimization.

Verifying PHP Installation

Check the installed PHP version:

php -v

The output should display PHP 8.3 or higher. List all loaded PHP extensions:

php -m

Verify that extensions like intl, mbstring, mysqlnd, and json appear in the list. Create a PHP info file for detailed configuration review:

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

Add the following content:

<?php
phpinfo();
?>

Restart Apache to load the PHP module:

sudo systemctl restart httpd

Access http://your-server-ip/info.php in your browser. The PHP information page confirms successful PHP integration with Apache. Remove this file after verification for security:

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

Step 5: Install Composer

Composer revolutionized PHP dependency management and is the recommended method for installing CodeIgniter 4. This package manager downloads framework files and manages updates efficiently.

Download the Composer installer using curl:

cd ~
curl -sS https://getcomposer.org/installer | php

The installer verifies integrity and downloads the latest Composer version. Move Composer to a global location for system-wide access:

sudo mv composer.phar /usr/local/bin/composer

Set executable permissions:

sudo chmod +x /usr/local/bin/composer

Verify Composer installation:

composer --version

Composer displays its version number, confirming successful installation. Using Composer offers significant advantages over manual installation, including automatic dependency resolution, simple update commands, and integration with modern PHP development workflows.

Step 6: Install CodeIgniter 4 Using Composer

Composer streamlines CodeIgniter installation by handling all dependencies automatically. This method ensures you always receive the latest stable version with all required components.

Creating Project Directory

Navigate to Apache’s web root directory:

cd /var/www/html

Create a new CodeIgniter project using Composer:

sudo composer create-project codeigniter4/appstarter codeigniter

The appstarter package includes a clean application structure without framework development files. Composer downloads CodeIgniter 4.6.x and all dependencies, creating a complete project structure. This process takes a few minutes depending on internet connection speed.

Setting Directory Permissions

Proper file permissions prevent security vulnerabilities while allowing Apache to serve content. Change ownership to the Apache user:

sudo chown -R apache:apache /var/www/html/codeigniter

Set directory permissions to 755:

sudo chmod -R 755 /var/www/html/codeigniter

Make the writable directory writable by the web server:

sudo chmod -R 777 /var/www/html/codeigniter/writable

The writable directory stores cache files, logs, and session data. While 777 permissions work for development, production environments should use more restrictive permissions with proper ownership.

Understanding CodeIgniter Directory Structure

CodeIgniter 4 organizes files into logical directories. The app directory contains your application code including controllers, models, and views. The public folder serves as the document root and contains the front controller index.php. The writable directory stores cache, logs, and uploads. The vendor folder holds Composer dependencies. Configuration files reside in app/Config, providing centralized settings management. Understanding this structure helps organize code effectively and leverage framework features.

Step 7: Configure Apache Virtual Host

Virtual hosts enable Apache to serve multiple websites from a single server. Proper virtual host configuration ensures CodeIgniter routes function correctly.

Creating Virtual Host File

Navigate to Apache’s configuration directory:

cd /etc/httpd/conf.d/

Create a new configuration file for CodeIgniter:

sudo nano codeigniter.conf

Add the following virtual host configuration:

<VirtualHost *:80>
    ServerName your-domain.com
    ServerAlias www.your-domain.com
    DocumentRoot /var/www/html/codeigniter/public

    <Directory /var/www/html/codeigniter/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /var/log/httpd/codeigniter_error.log
    CustomLog /var/log/httpd/codeigniter_access.log combined
</VirtualHost>

The DocumentRoot points to the public directory, not the project root. This configuration hides sensitive application files from web access. The AllowOverride All directive enables .htaccess files for URL rewriting, essential for clean URLs without index.php in the path.

Enabling Virtual Host and Restarting Apache

Test the Apache configuration for syntax errors:

sudo apachectl configtest

A “Syntax OK” message indicates correct configuration. Restart Apache to apply changes:

sudo systemctl restart httpd

For local testing without a registered domain, edit the hosts file:

sudo nano /etc/hosts

Add an entry mapping your server’s IP to the domain:

127.0.0.1 your-domain.com

Production deployments require proper DNS configuration pointing the domain to your server’s public IP address.

Step 8: Configure CodeIgniter 4

CodeIgniter requires minimal configuration to start development. Environment-specific settings allow different configurations for development, testing, and production.

Environment Configuration

Navigate to the CodeIgniter project directory:

cd /var/www/html/codeigniter

Copy the environment file template:

sudo cp env .env

Edit the .env file:

sudo nano .env

Set the environment to development mode:

CI_ENVIRONMENT = development

Development mode displays detailed error messages for debugging. Configure the base URL to match your domain:

app.baseURL = 'http://your-domain.com'

Proper base URL configuration ensures assets load correctly and routing functions as expected.

Database Configuration

Configure database connection parameters in the .env file:

database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_database_user
database.default.password = your_secure_password
database.default.DBDriver = MySQLi

Create the database if it doesn’t exist:

mysql -u root -p
CREATE DATABASE your_database_name;
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_database_user'@'localhost' IDENTIFIED BY 'your_secure_password';
FLUSH PRIVILEGES;
EXIT;

Test the database connection by creating a simple controller that queries the database.

Additional Configuration Settings

Generate a secure encryption key for data encryption and CSRF protection:

php spark key:generate

This command automatically updates the .env file with a secure random key. Configure session settings, timezone, and other application-specific parameters in the .env file or app/Config directory files.

Step 9: Test CodeIgniter Installation

Verifying the installation ensures all components work together correctly. CodeIgniter provides multiple methods for testing.

Testing Through Apache

Access your configured domain or server IP through a web browser:

http://your-domain.com

The default CodeIgniter welcome page displays, featuring the framework logo and version information. This page confirms Apache serves the application correctly and CodeIgniter’s routing system functions properly. If errors appear, check Apache error logs:

sudo tail -f /var/log/httpd/codeigniter_error.log

Error logs reveal configuration issues, missing extensions, or permission problems.

Creating Test Controller

Create a simple controller to verify functionality:

sudo nano app/Controllers/Test.php

Add the following code:

<?php

namespace App\Controllers;

class Test extends BaseController
{
    public function index()
    {
        return "CodeIgniter is working correctly!";
    }
}

Access the test controller:

http://your-domain.com/test

The message confirms controllers execute properly and routing works as expected.

Step 10: Security Hardening

Production deployments require additional security measures beyond basic installation.

File and Directory Permissions

Restrict access to sensitive configuration files:

sudo chmod 600 /var/www/html/codeigniter/.env

The .env file contains database credentials and encryption keys that must remain protected. Remove write permissions from directories that don’t require modification:

sudo chmod -R 755 /var/www/html/codeigniter/app

Only the writable directory should have extensive permissions for logging and caching.

Production Environment Settings

Switch to production mode in the .env file:

CI_ENVIRONMENT = production

Production mode suppresses detailed error messages, preventing information disclosure. Configure proper error logging instead:

logger.threshold = 4

Remove index.php from URLs by ensuring the .htaccess file in the public directory contains proper rewrite rules.

SELinux Configuration

Rocky Linux 10 includes SELinux for mandatory access control. Set proper security contexts for web files:

sudo chcon -R -t httpd_sys_content_t /var/www/html/codeigniter

Allow Apache to write to the writable directory:

sudo chcon -R -t httpd_sys_rw_content_t /var/www/html/codeigniter/writable

If issues persist, check SELinux logs:

sudo ausearch -m avc -ts recent

These commands ensure SELinux policies don’t prevent Apache from accessing application files while maintaining security boundaries.

Step 11: Performance Optimization

Optimizing performance ensures fast page loads and efficient resource utilization.

Enabling OPcache

OPcache dramatically improves PHP performance by caching compiled bytecode. Verify OPcache is installed:

php -m | grep -i opcache

Configure OPcache settings in /etc/php.ini:

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

These settings balance memory usage with performance gains.

CodeIgniter Caching

Enable output caching for frequently accessed pages:

$this->cachePage(3600); // Cache for 1 hour

Configure cache drivers in app/Config/Cache.php. File-based caching works well for small sites, while Redis or Memcached suit high-traffic applications.

Apache Performance Tuning

Enable compression in Apache configuration:

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

Add compression directives:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>

Compression reduces bandwidth usage and improves load times. Configure KeepAlive settings for persistent connections and adjust MaxClients based on available RAM.

Troubleshooting Common Issues

Even careful installations encounter occasional issues. Understanding common problems speeds resolution.

Apache 403 Forbidden Error

Forbidden errors indicate permission or configuration issues. Verify directory permissions allow Apache to read files:

ls -la /var/www/html/codeigniter/public

Check SELinux contexts and temporarily set permissive mode for testing:

sudo setenforce 0

If issues resolve, SELinux contexts need adjustment. Review Apache configuration for correct DocumentRoot paths and Directory directives.

PHP Extensions Not Loaded

Missing extensions cause fatal errors. Install missing extensions:

sudo dnf install php-extension-name

Restart Apache after installing extensions:

sudo systemctl restart httpd

Check extension configuration files in /etc/php.d/ to ensure extensions load correctly.

Database Connection Errors

Connection failures stem from incorrect credentials or service issues. Verify MariaDB runs:

sudo systemctl status mariadb

Test database credentials manually:

mysql -u your_database_user -p your_database_name

Check firewall rules if the database runs on a separate server. Verify hostname settings match the database server location.

404 Errors or Routing Issues

URL routing problems often relate to mod_rewrite configuration. Enable mod_rewrite:

sudo dnf install mod_rewrite -y

Verify .htaccess files exist in the public directory with proper rewrite rules. Ensure AllowOverride All is set in the virtual host configuration.

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