Prerequisites

Basic Linux Command line, Text editor usage, Web Server concepts, Database Funsamentals, Networking Basics, DNS configurations knowledge, Ability to modify firewall rules(ufw, firewalld or iptables)

What is LAMP Stack Installation?

LAMP stack installation is the process of setting up four critical open-source components—Linux, Apache, MySQL/MariaDB, and PHP—to create a powerful web development environment. This integrated platform enables you to deploy dynamic websites and web applications efficiently. The installation typically takes 15-30 minutes and provides a production-ready foundation for hosting WordPress, custom web applications, and database-driven sites.

Quick Installation Commands (Ubuntu/Debian):

# Update system packages
sudo apt update && sudo apt upgrade -y

# Install Apache web server
sudo apt install apache2 -y

# Install MySQL database server
sudo apt install mysql-server -y

# Install PHP and essential modules
sudo apt install php libapache2-mod-php php-mysql -y

# Restart Apache to activate PHP
sudo systemctl restart apache2

Table of Contents

  1. What is a LAMP Stack and Why Use It?
  2. How to Install Apache Web Server on Linux
  3. How to Install MySQL Database Server
  4. How to Install PHP and Configure Apache Integration
  5. How to Test Your LAMP Stack Installation
  6. How to Create Virtual Hosts for Multiple Websites
  7. How to Secure Your LAMP Stack Configuration
  8. How to Optimize LAMP Performance
  9. FAQ: Common LAMP Stack Questions
  10. Troubleshooting LAMP Stack Issues

What is a LAMP Stack and Why Use It?

The LAMP stack represents the industry-standard foundation for web development, combining four essential open-source technologies. Consequently, this web development stack powers millions of websites worldwide, including major platforms like Facebook and WordPress.

LAMP Stack Components Explained

Linux serves as the operating system foundation, providing stability, security, and reliability. Most importantly, Linux offers robust file permissions and process management essential for web servers.

Apache functions as the HTTP server, handling client requests and serving web content. Furthermore, Apache supports virtual hosts, enabling multiple websites on a single server.

MySQL (or MariaDB) provides relational database management, storing and organizing structured data efficiently. Additionally, MySQL integrates seamlessly with PHP for dynamic content generation.

PHP enables server-side scripting, creating dynamic web pages by processing code before sending HTML to browsers. Moreover, PHP connects applications to databases, enabling interactive user experiences.

Why Choose LAMP Stack Installation?

Organizations choose LAMP stack installation because it delivers enterprise-grade capabilities without licensing costs. Similarly, the open-source nature ensures continuous security updates and community support. The LAMP architecture also provides excellent scalability, growing from small blogs to high-traffic platforms.

Key Benefits:

  • Zero licensing costs for all components
  • Extensive community support with millions of developers
  • Proven reliability powering major web platforms
  • Flexible configuration supporting diverse applications
  • Cross-distribution compatibility across Ubuntu, CentOS, Debian

How to Install Apache Web Server on Linux

Apache web server installation forms the critical first step in LAMP stack installation. Therefore, properly configuring Apache ensures optimal web server performance and security.

Installing Apache on Ubuntu/Debian

Begin your LAMP stack installation by updating system repositories and installing the Apache package:

# Update package repositories
sudo apt update

# Install Apache2 web server
sudo apt install apache2 -y

# Verify Apache installation
apache2 -v

Installing Apache on CentOS/RHEL

For Red Hat-based distributions, the Apache package uses different naming conventions:

# Update system packages
sudo yum update -y

# Install Apache HTTP server
sudo yum install httpd -y

# Verify httpd installation
httpd -v

Starting and Enabling Apache Service

After completing Apache installation, enable and start the web server service:

# Start Apache service immediately
sudo systemctl start apache2  # Ubuntu/Debian
sudo systemctl start httpd    # CentOS/RHEL

# Enable Apache to start on boot
sudo systemctl enable apache2  # Ubuntu/Debian
sudo systemctl enable httpd    # CentOS/RHEL

# Check Apache service status
sudo systemctl status apache2  # Ubuntu/Debian

Configuring Firewall for Apache

Allow HTTP and HTTPS traffic through your firewall to enable external access:

# Ubuntu/Debian with UFW
sudo ufw allow 'Apache Full'
sudo ufw enable
sudo ufw status

# CentOS/RHEL with firewalld
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Verifying Apache Installation

Test your Apache installation by accessing the default web page:

# Check Apache is listening on port 80
sudo ss -tlnp | grep :80

# Test local access
curl http://localhost

# Get server IP address
ip addr show

Navigate to http://your-server-ip in a web browser. You should see the Apache default page, confirming successful installation.


How to Install MySQL Database Server

MySQL database installation provides the data storage layer essential for dynamic web applications. Alternatively, MariaDB offers a drop-in replacement with enhanced performance.

Installing MySQL on Ubuntu/Debian

Install MySQL server and secure the initial configuration:

# Install MySQL server package
sudo apt install mysql-server -y

# Check MySQL version
mysql --version

# Start MySQL service
sudo systemctl start mysql

# Enable MySQL on boot
sudo systemctl enable mysql

Installing MariaDB as MySQL Alternative

MariaDB provides an excellent MySQL alternative for LAMP stack installation:

# Install MariaDB server
sudo apt install mariadb-server -y

# Start MariaDB service
sudo systemctl start mariadb

# Enable MariaDB on boot
sudo systemctl enable mariadb

Securing MySQL Database Installation

Run the security script to remove insecure default settings:

# Execute MySQL security script
sudo mysql_secure_installation

The security wizard guides you through critical hardening steps:

  1. Set root password – Create a strong password for the MySQL root user
  2. Remove anonymous users – Delete users without passwords
  3. Disable root remote login – Prevent root access from network
  4. Remove test database – Delete the publicly accessible test database
  5. Reload privilege tables – Apply security changes immediately

Creating MySQL Database and User

Establish a dedicated database and user for web applications:

# Access MySQL shell as root
sudo mysql -u root -p

# Create new database
CREATE DATABASE webapp_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Create database user with password
CREATE USER 'webapp_user'@'localhost' IDENTIFIED BY 'strong_password_here';

# Grant privileges to user
GRANT ALL PRIVILEGES ON webapp_db.* TO 'webapp_user'@'localhost';

# Apply privilege changes
FLUSH PRIVILEGES;

# Exit MySQL shell
EXIT;

Verifying MySQL Installation

Test database connectivity and functionality:

# Test MySQL connection
mysql -u webapp_user -p -e "SHOW DATABASES;"

# Check MySQL service status
sudo systemctl status mysql

# View MySQL error log
sudo tail -f /var/log/mysql/error.log

How to Install PHP and Configure Apache Integration

PHP installation completes the core LAMP stack installation, enabling dynamic content generation. Furthermore, proper PHP configuration ensures optimal performance and security.

Installing PHP with Essential Modules

Install PHP along with critical modules for database connectivity and Apache integration:

# Install PHP and essential extensions (Ubuntu/Debian)
sudo apt install php libapache2-mod-php php-mysql -y

# Install additional PHP modules
sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-zip -y

# Verify PHP installation
php -v

Installing PHP on CentOS/RHEL

Red Hat systems require slightly different package names:

# Install PHP and modules
sudo yum install php php-mysqlnd php-gd php-xml php-mbstring -y

# Restart Apache to load PHP module
sudo systemctl restart httpd

Configuring PHP for Apache

Optimize PHP settings in the main configuration file:

# Edit PHP configuration file
sudo nano /etc/php/8.1/apache2/php.ini  # Ubuntu (version may vary)
sudo nano /etc/php.ini                   # CentOS

Key PHP Configuration Settings:

# Increase memory limit for larger applications
memory_limit = 256M

# Set maximum file upload size
upload_max_filesize = 64M
post_max_size = 64M

# Configure maximum execution time
max_execution_time = 300

# Enable error reporting for development
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log

# Set timezone
date.timezone = America/New_York

Configuring Apache to Prefer PHP Files

Modify Apache configuration to prioritize PHP index files:

# Edit Apache directory configuration
sudo nano /etc/apache2/mods-enabled/dir.conf  # Ubuntu/Debian
sudo nano /etc/httpd/conf/httpd.conf          # CentOS/RHEL

Update DirectoryIndex to prioritize index.php:

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

Restarting Apache to Apply PHP Configuration

Restart Apache to activate all PHP changes:

# Restart Apache service
sudo systemctl restart apache2  # Ubuntu/Debian
sudo systemctl restart httpd    # CentOS/RHEL

# Verify Apache loaded PHP module
apache2ctl -M | grep php  # Ubuntu/Debian
httpd -M | grep php       # CentOS/RHEL

How to Test Your LAMP Stack Installation

Testing your LAMP stack installation verifies all components communicate correctly. Additionally, proper testing identifies configuration issues before deployment.

Creating PHP Info Test File

Create a PHP information page to verify PHP functionality:

# Create PHP test file in web root
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

# Set proper permissions
sudo chown www-data:www-data /var/www/html/info.php  # Ubuntu/Debian
sudo chown apache:apache /var/www/html/info.php      # CentOS/RHEL

# Set file permissions
sudo chmod 644 /var/www/html/info.php

Access the PHP info page at http://your-server-ip/info.php. The page displays comprehensive PHP configuration details, confirming successful PHP integration.

Testing MySQL-PHP Connectivity

Create a script to verify database connectivity:

# Create MySQL connection test file
sudo nano /var/www/html/db-test.php

Add PHP database connection code:

<?php
$servername = "localhost";
$username = "webapp_user";
$password = "strong_password_here";
$database = "webapp_db";

// Create MySQL connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "<h1>Database Connection Successful!</h1>";
echo "<p>Connected to database: " . $database . "</p>";
echo "<p>MySQL version: " . $conn->server_info . "</p>";

$conn->close();
?>

Access http://your-server-ip/db-test.php to verify database connectivity. Successful connection confirms complete LAMP stack integration.

Removing Test Files for Security

Delete test files after verification to prevent security risks:

# Remove PHP info file
sudo rm /var/www/html/info.php

# Remove database test file
sudo rm /var/www/html/db-test.php

How to Create Virtual Hosts for Multiple Websites

Virtual hosts enable hosting multiple websites on a single LAMP stack installation. Consequently, you can serve different domains from one server efficiently.

Creating Document Root Directory

Establish separate directories for each website:

# Create directory for first website
sudo mkdir -p /var/www/example.com/public_html

# Create directory for second website
sudo mkdir -p /var/www/testsite.com/public_html

# Set ownership to web server user
sudo chown -R www-data:www-data /var/www/example.com  # Ubuntu/Debian
sudo chown -R apache:apache /var/www/example.com      # CentOS/RHEL

# Set proper permissions
sudo chmod -R 755 /var/www

Creating Sample Index Files

Create test index pages for each virtual host:

# Create index file for first site
sudo nano /var/www/example.com/public_html/index.html

Add sample HTML content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Example.com</title>
</head>
<body>
    <h1>Success! Example.com virtual host is working!</h1>
    <p>This is the Example.com website on your LAMP stack.</p>
</body>
</html>

Configuring Apache Virtual Host Files

Create virtual host configuration for each domain:

# Create virtual host configuration (Ubuntu/Debian)
sudo nano /etc/apache2/sites-available/example.com.conf

# Create virtual host configuration (CentOS/RHEL)
sudo nano /etc/httpd/conf.d/example.com.conf

Add virtual host configuration:

<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    
    <Directory /var/www/example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>

Enabling Virtual Hosts

Activate virtual host configurations on Ubuntu/Debian:

# Enable virtual host site
sudo a2ensite example.com.conf

# Enable rewrite module
sudo a2enmod rewrite

# Test Apache configuration
sudo apache2ctl configtest

# Reload Apache configuration
sudo systemctl reload apache2

On CentOS/RHEL, simply restart Apache after creating configuration files:

# Test httpd configuration
sudo httpd -t

# Restart httpd service
sudo systemctl restart httpd

Configuring Local DNS for Testing

For testing purposes, modify your hosts file:

# Edit hosts file
sudo nano /etc/hosts

Add domain mappings:

127.0.0.1    example.com www.example.com
127.0.0.1    testsite.com www.testsite.com

How to Secure Your LAMP Stack Configuration

Securing your LAMP stack installation protects against vulnerabilities and unauthorized access. Moreover, security hardening should occur immediately after installation.

Updating All LAMP Stack Components

Regular updates patch security vulnerabilities:

# Update all packages (Ubuntu/Debian)
sudo apt update && sudo apt upgrade -y

# Update all packages (CentOS/RHEL)
sudo yum update -y

# Check for security updates only
sudo apt list --upgradable | grep -i security

Configuring Apache Security Headers

Add security headers to Apache configuration:

# Edit Apache security configuration
sudo nano /etc/apache2/conf-available/security.conf  # Ubuntu/Debian
sudo nano /etc/httpd/conf/httpd.conf                 # CentOS/RHEL

Add security headers:

# Hide Apache version information
ServerTokens Prod
ServerSignature Off

# Enable security headers
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"

Enable headers module and reload Apache:

# Enable headers module
sudo a2enmod headers  # Ubuntu/Debian

# Restart Apache
sudo systemctl restart apache2

Hardening MySQL Security Configuration

Strengthen MySQL security beyond initial setup:

# Access MySQL as root
sudo mysql -u root -p

# Disable remote root login
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');

# Remove anonymous users
DELETE FROM mysql.user WHERE User='';

# Remove test database
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';

# Flush privileges
FLUSH PRIVILEGES;
EXIT;

Configuring PHP Security Settings

Harden PHP configuration against common vulnerabilities:

# Edit PHP configuration
sudo nano /etc/php/8.1/apache2/php.ini

Security-focused PHP settings:

# Disable dangerous functions
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

# Disable file uploads if not needed
file_uploads = Off

# Restrict file access
open_basedir = /var/www:/tmp

# Hide PHP version
expose_php = Off

# Enable strict error reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
log_errors = On

# Session security
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1

Implementing Firewall Rules

Configure restrictive firewall rules permitting only necessary traffic:

# Ubuntu/Debian UFW configuration
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 'Apache Full'
sudo ufw enable

# CentOS/RHEL firewalld configuration
sudo firewall-cmd --set-default-zone=public
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Installing and Configuring Fail2Ban

Fail2Ban provides automated intrusion prevention:

# Install Fail2Ban
sudo apt install fail2ban -y  # Ubuntu/Debian
sudo yum install fail2ban -y  # CentOS/RHEL

# Create local configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Edit Fail2Ban configuration
sudo nano /etc/fail2ban/jail.local

Configure Apache and SSH protection:

[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5

[sshd]

enabled = true port = ssh logpath = /var/log/auth.log

[apache-auth]

enabled = true port = http,https logpath = /var/log/apache2/error.log

Start and enable Fail2Ban:

# Start Fail2Ban service
sudo systemctl start fail2ban

# Enable on boot
sudo systemctl enable fail2ban

# Check Fail2Ban status
sudo fail2ban-client status

How to Optimize LAMP Performance

Optimizing your LAMP stack installation maximizes performance and resource efficiency. Furthermore, proper tuning handles increased traffic loads effectively.

Enabling Apache Performance Modules

Activate Apache modules enhancing performance:

# Enable compression module
sudo a2enmod deflate

# Enable caching module
sudo a2enmod expires
sudo a2enmod headers

# Enable HTTP/2 support
sudo a2enmod http2

# Restart Apache
sudo systemctl restart apache2

Configuring Apache MPM Settings

Optimize Multi-Processing Module for your server resources:

# Edit MPM prefork configuration
sudo nano /etc/apache2/mods-available/mpm_prefork.conf

Tuned MPM settings for 4GB RAM server:

<IfModule mpm_prefork_module>
    StartServers             5
    MinSpareServers          5
    MaxSpareServers          10
    MaxRequestWorkers        150
    MaxConnectionsPerChild   3000
</IfModule>

Optimizing MySQL Performance

Tune MySQL configuration for improved performance:

# Edit MySQL configuration
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf  # Ubuntu/Debian
sudo nano /etc/my.cnf                         # CentOS/RHEL

Performance-oriented MySQL settings:

[mysqld]
# Connection settings
max_connections = 200
connect_timeout = 10
wait_timeout = 600

# Buffer pool settings (set to 70% of available RAM)
innodb_buffer_pool_size = 2G
innodb_log_file_size = 512M
innodb_log_buffer_size = 64M

# Query cache (for MySQL 5.7 and earlier)
query_cache_type = 1
query_cache_size = 128M
query_cache_limit = 4M

# Temporary tables
tmp_table_size = 128M
max_heap_table_size = 128M

Restart MySQL to apply changes:

sudo systemctl restart mysql

Enabling PHP OpCache

OpCache significantly improves PHP performance by caching compiled scripts:

# Install PHP OpCache extension
sudo apt install php-opcache -y

# Edit OpCache configuration
sudo nano /etc/php/8.1/apache2/conf.d/10-opcache.ini

Optimal OpCache settings:

opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1

Restart Apache to enable OpCache:

sudo systemctl restart apache2

Implementing Caching Strategies

Configure browser caching and compression:

# Create caching configuration
sudo nano /etc/apache2/conf-available/caching.conf

Add caching rules:

<IfModule mod_expires.c>
    ExpiresActive On
    
    # Images
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    
    # CSS and JavaScript
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    
    # Fonts
    ExpiresByType font/woff2 "access plus 1 year"
</IfModule>

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

Enable the caching configuration:

sudo a2enconf caching
sudo systemctl reload apache2

FAQ: Common LAMP Stack Questions

How long does LAMP stack installation take?

Complete LAMP stack installation typically requires 15-30 minutes on a fresh Linux system. However, additional configuration and optimization may extend setup time to 1-2 hours. Installation speed depends on internet connection, server resources, and distribution choice.

Can I use Nginx instead of Apache in LAMP?

Absolutely! Many administrators prefer Nginx for its performance characteristics, creating what’s called a LEMP stack (Linux, Nginx, MySQL, PHP). Nginx excels at serving static content and handling concurrent connections. Nevertheless, Apache remains popular for its extensive module ecosystem and .htaccess support.

Should I choose MySQL or MariaDB for LAMP?

Both databases work excellently in LAMP stack installations. MariaDB offers enhanced performance, additional storage engines, and active community development. Conversely, MySQL provides broader compatibility with legacy applications. Either choice delivers production-ready database functionality.

How do I install multiple PHP versions on LAMP?

Multiple PHP versions coexist using PHP-FPM with Apache. Install different PHP versions through package repositories, configure separate FPM pools, and use Apache’s SetHandler directive per virtual host. This approach enables running legacy and modern applications simultaneously.

What server specifications does LAMP stack require?

Minimum LAMP stack installation runs on 1GB RAM and 1 CPU core for development. However, production environments typically require 2-4GB RAM, 2+ CPU cores, and adequate disk space. Requirements scale based on expected traffic, database size, and application complexity.

How secure is LAMP stack out of the box?

Default LAMP stack installation provides basic security but requires hardening for production use. Immediately run mysql_secure_installation, configure firewalls, disable unnecessary services, and implement regular updates. Additionally, configure SSL/TLS certificates, security headers, and access controls.

Can LAMP stack handle high-traffic websites?

Properly optimized LAMP installations handle millions of daily visitors. Implement caching mechanisms, optimize database queries, configure load balancing, and utilize CDNs for static content. Sites like Wikipedia and WordPress.com demonstrate LAMP’s enterprise scalability.

How do I backup my LAMP stack configuration?

Backup strategies include database dumps using mysqldump, web root directories via rsync, and configuration files under /etc. Automated backup scripts combined with offsite storage ensure disaster recovery capability. Additionally, document custom configurations and virtual host settings.


Troubleshooting LAMP Stack Issues

Apache Won’t Start After Installation

Symptoms: Apache service fails to start, error messages in system logs

Diagnostic Commands:

# Check Apache service status
sudo systemctl status apache2

# View detailed Apache errors
sudo journalctl -u apache2 -n 50

# Test Apache configuration syntax
sudo apache2ctl configtest

# Check if port 80 is already in use
sudo ss -tlnp | grep :80

Common Solutions:

  1. Port 80 conflict – Another service uses port 80. Identify and stop conflicting service:
sudo systemctl stop nginx  # If nginx is running
  1. Configuration syntax errors – Review error messages from configtest and fix syntax issues in virtual host files
  2. Permission problems – Ensure Apache user has access to document root:
sudo chown -R www-data:www-data /var/www
sudo chmod -R 755 /var/www

MySQL Connection Refused Errors

Symptoms: Applications cannot connect to MySQL, “Connection refused” errors

Diagnostic Commands:

# Verify MySQL is running
sudo systemctl status mysql

# Check MySQL is listening on port 3306
sudo ss -tlnp | grep 3306

# Review MySQL error log
sudo tail -100 /var/log/mysql/error.log

# Test local MySQL connection
mysql -u root -p -e "SELECT VERSION();"

Common Solutions:

  1. MySQL not running – Start MySQL service:
sudo systemctl start mysql
sudo systemctl enable mysql
  1. Bind address configuration – Edit MySQL configuration to listen on correct interface:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
# Change: bind-address = 127.0.0.1
sudo systemctl restart mysql
  1. Firewall blocking connections – Allow MySQL through firewall:
sudo ufw allow 3306/tcp

PHP Not Processing, Shows Source Code

Symptoms: Browser displays PHP code instead of executing it, .php files download

Diagnostic Commands:

# Verify PHP module is loaded
apache2ctl -M | grep php

# Check PHP installation
php -v

# Review Apache error log
sudo tail -50 /var/log/apache2/error.log

Common Solutions:

  1. PHP module not enabled – Install and enable PHP module:
sudo apt install libapache2-mod-php
sudo a2enmod php8.1
sudo systemctl restart apache2
  1. Incorrect MIME type – Verify Apache recognizes .php files:
# Add to Apache configuration if missing
echo "AddType application/x-httpd-php .php" | sudo tee -a /etc/apache2/mods-enabled/php8.1.conf
sudo systemctl restart apache2
  1. DirectoryIndex misconfiguration – Ensure index.php is in DirectoryIndex list as shown earlier

Permission Denied Errors

Symptoms: 403 Forbidden errors, file upload failures, “Permission denied” in logs

Diagnostic Commands:

# Check file ownership
ls -la /var/www/html

# View SELinux denials (RHEL/CentOS)
sudo ausearch -m avc -ts recent

# Check directory permissions
namei -l /var/www/html/index.php

Common Solutions:

  1. Incorrect ownership – Set proper web server user ownership:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
sudo chmod 644 /var/www/html/*.php
  1. SELinux blocking access – Configure SELinux context (RHEL/CentOS):
sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"
sudo restorecon -Rv /var/www/html
  1. Parent directory permissions – Ensure all parent directories allow traversal

Virtual Host Not Working

Symptoms: Default page appears instead of virtual host, wrong site displays

Diagnostic Commands:

# List enabled sites
apache2ctl -S  # Ubuntu/Debian
httpd -S       # CentOS/RHEL

# Check virtual host syntax
sudo apache2ctl -t

# Review access log for correct virtual host
sudo tail -f /var/log/apache2/access.log

Common Solutions:

  1. Virtual host not enabled – Enable site configuration:
sudo a2ensite example.com.conf
sudo systemctl reload apache2
  1. DNS not configured – Add domain to /etc/hosts for local testing:
echo "127.0.0.1 example.com" | sudo tee -a /etc/hosts
  1. ServerName mismatch – Verify ServerName matches requested domain exactly in virtual host configuration

High Memory Usage

Symptoms: Server becomes slow, out of memory errors, processes killed

Diagnostic Commands:

# Monitor memory usage
free -h

# Identify memory-consuming processes
ps aux --sort=-%mem | head -10

# Check Apache process count
ps aux | grep apache2 | wc -l

# Monitor MySQL memory usage
mysql -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size';"

Common Solutions:

  1. Apache MaxRequestWorkers too high – Reduce MaxRequestWorkers in MPM configuration to match available RAM
  2. MySQL buffer pool oversized – Lower innodb_buffer_pool_size to 50-70% of available RAM:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
# Set: innodb_buffer_pool_size = 1G
sudo systemctl restart mysql
  1. PHP memory limit excessive – Reduce PHP memory_limit in php.ini:
sudo nano /etc/php/8.1/apache2/php.ini
# Set: memory_limit = 128M
sudo systemctl restart apache2

Additional Resources

Official Documentation

Related LinuxTips.pro Articles

Security Resources

Community Resources


Conclusion

LAMP stack installation provides the foundational infrastructure powering millions of websites globally. Throughout this comprehensive guide, you’ve learned to install each component systematically, configure virtual hosts for multiple sites, implement security hardening, and optimize performance for production workloads.

Remember that LAMP stack installation is merely the beginning of your web development journey. Consequently, continue exploring advanced topics like load balancing, database replication, and containerization to scale your infrastructure. Moreover, maintain regular update schedules, monitor system resources, and implement robust backup strategies to ensure long-term reliability.

The versatility of LAMP stack installation enables hosting everything from simple blogs to complex enterprise applications. By mastering these fundamental skills, you’ve acquired the expertise to deploy, manage, and troubleshoot production web servers confidently.

Mark as Complete

Did you find this guide helpful? Track your progress by marking it as completed.