
Deploy Apache, MariaDB, and PHP with security, performance, and best practices
If you’re looking to install LAMP stack Ubuntu, this guide walks you through deploying Apache, MariaDB, and PHP the right way, with security, performance, and best practices built in from the start rather than bolted on afterward.
Instead of simply showing commands to copy and paste, we’ll explain why each component is installed, how it interacts with the rest of the stack, and where small configuration changes can significantly improve security, maintainability, and overall performance. By the end of this guide, you’ll have a clean, production-ready LAMP environment suitable for hosting real-world websites and applications.
For this tutorial, we’ll assume you already have:
- A clean Ubuntu Server 22.04, 24.04, or 26.04 installation • Root or sudo privileges
- SSH access to the server
- A public IP address
- Internet connectivity
No web server, database server, or PHP packages should already be installed.
LAMP Stack Overview
LAMP includes Linux, Apache, MariaDB, and PHP. Apache handles web requests, PHP processes dynamic pages, and MariaDB stores application data.
Secure Your Server Fast
Linux VPS
Step 1: Update Your Ubuntu Server
The very first task on any freshly installed server should always be updating the operating system.
Ubuntu installation media can quickly become outdated, meaning your server may already be missing hundreds of security patches or package updates immediately after installation. Starting with the latest package versions reduces compatibility issues and ensures you’re installing the most recent software available through the Ubuntu repositories.
Refresh the package index:
- sudo apt update
Next, upgrade all installed packages:
- sudo apt upgrade -y
If additional kernel updates are installed, reboot the server before
continuing. • sudo reboot
Once the server comes back online, reconnect through SSH and verify the operating system version.
- lsb_release -a
Example output:
Distributor ID: Ubuntu Description: Ubuntu 24.04 LTS
Release: 24.04 Codename: noble
You can also check whether a reboot is still pending:
- [ -f /var/run/reboot-required ] && echo “Reboot required” If nothing is displayed, your system is fully updated.
Why updating first matters
Skipping this step may not cause immediate problems, but it often introduces subtle issues later during deployment.
Step 2: Install Apache Web Server
Apache HTTP Server has been powering websites for more than two decades and remains one of the most reliable web servers available today. While alternatives such as Nginx have become increasingly popular, Apache continues to excel in environments where flexibility, compatibility, and extensive module support are important.
Its mature ecosystem makes it an excellent choice for hosting PHP applications, particularly WordPress, OpenCart, Magento, Laravel, and legacy business software that depends on Apache modules like mod_rewrite.
Install Apache using Ubuntu’s official repository:
- sudo apt install apache2 -y
Once the installation completes, configure Apache to start automatically every time the server boots.
- sudo systemctl enable apache2
Start the service immediately.
- sudo systemctl start apache2
Verify that Apache is running correctly.
- sudo systemctl status apache2
You should see output similar to:
- Active: active (running)
If the service is inactive or failed, avoid troubleshooting blindly. Always inspect the logs first.
• udo journalctl -u apache2 –no-pager
or
- sudo tail -50 /var/log/apache2/error.log
These logs almost always identify the exact cause of the problem, whether it’s a syntax error, port conflict, or missing module.
Understanding Apache’s Directory Structure
One reason Apache remains popular is its clean and modular configuration layout.
Most configuration files are stored under:
- /etc/apache2/
Some of the most important directories include:
| Directory | Purpose |
| /etc/apache2/apache2.conf | Main Apache configuration file. |
| /etc/apache2/sites-available/ | Stores Virtual Host configuration files. |
| /etc/apache2/sites-enabled/ | Contains enabled Virtual Hosts through symbolic links. |
| /etc/apache2/mods-available/ | Available Apache modules. |
| /etc/apache2/mods-enabled/ | Enabled modules loaded during startup. |
| /var/www/html/ | Default web root for the default website. |
| /var/log/apache2/ | Access and error logs. |
Rather than editing the main configuration file directly, Ubuntu encourages enabling or disabling websites and modules individually. This modular approach makes maintenance easier and significantly reduces the risk of breaking the web server during future changes.
Verify Apache Configuration
Before restarting Apache after any configuration change, always validate the configuration syntax.
Run:
- sudo apache2ctl configtest
Expected output:
- Syntax OK
This simple command takes only a second to execute but can save hours of troubleshooting. It detects missing directives, incorrect syntax, duplicate configurations, and other common mistakes before they cause Apache to fail during a restart.
Many experienced Linux administrators make it a habit to run apache2ctl configtest before every service reload, especially on production servers.
Step 3: Configure the Firewall
Before exposing your server to the internet, it’s important to restrict unnecessary network access. Ubuntu ships with UFW (Uncomplicated Firewall), a frontend for iptables/nftables that simplifies firewall management without sacrificing security.
Step 4: Install MariaDB
A web server alone cannot power modern applications. Content management systems, eCommerce platforms, customer portals, and APIs all rely on databases to store persistent information.
For this guide, we’ll install MariaDB, one of the most widely adopted relational database servers in the Linux ecosystem.
Install MariaDB:
- sudo apt install mariadb-server mariadb-client -y Once the installation finishes, configure the service to start automatically.
- sudo systemctl enable mariadb sudo systemctl start mariadb
Verify that the database server is running.
- sudo systemctl status mariadb
Expected status:
Active: active (running)
If MariaDB fails to start, inspect the logs instead of attempting random fixes. • sudo journalctl -u mariadb –no-pager
or
- sudo tail -50 /var/log/mysql/error.log
Logs almost always provide the exact reason for startup failures.
Secure Your Database Server
A default MariaDB installation prioritizes ease of deployment rather than security. Ubuntu provides an interactive script that applies several recommended security changes. Run:
- sudo mysql_secure_installation
Run sudo mysql_secure_installation, remove anonymous users, remove the test database, reload privileges, and use socket authentication where appropriate.
Verify Database Access
Once the secure installation completes, verify that you can access MariaDB successfully. • sudo mysql
You should enter the MariaDB shell.
Example:
- Welcome to the MariaDB monitor.
Exit the shell using:
- exit;
If you can log in successfully, your database server is ready for application deployment.
Do not use the MariaDB root account for applications; create a dedicated database user for each site.
Step 5: Install PHP and Required Extensions
With Apache and MariaDB running, the next step is installing PHP. PHP remains one of the most widely used server-side programming languages and continues to power a significant portion of the modern web, including platforms such as WordPress, OpenCart, Magento, Drupal, and countless custom applications.
A common mistake is installing only the base PHP package. While this may work for simple scripts, most production applications require additional extensions for database connectivity, image processing, caching, API integrations, and various application-specific features.
Instead of repeatedly installing missing modules later, it’s best to deploy a solid PHP foundation from the beginning.
Install PHP along with commonly required extensions:
- sudo apt install php php-cli php-common php-fpm php-mysql \ php-curl php-gd php-mbstring php-xml php-xmlrpc \ php-zip php-intl php-bcmath php-opcache -y
After installation, verify the installed PHP version.
- php -v
Example output:
- PHP 8.3.6 (cli)
Depending on your Ubuntu version, the installed PHP release may vary.
Understanding the Installed PHP Extensions
These extensions cover database access, image handling, API requests, ZIP support, localization, and OPcache.
PHP-FPM vs Traditional mod_php
PHP-FPM is preferred for modern production deployments because it handles PHP processes more efficiently than older mod_php setups.
Verify PHP Module Availability
To see which extensions are currently loaded:
- php -m
You should see modules such as:
- mysqli
curl
gd
mbstring
intl
xml
zip
Zend OPcache
Verifying modules early helps avoid application deployment issues later.
Step 6 – Configure PHP for Production
The default PHP configuration is designed to maximize compatibility rather than performance.
While the defaults work, they often need adjustment for production workloads. First locate the active configuration file:
php –ini
Typical output:
Loaded Configuration File: /etc/php/8.x/apache2/php.ini
Open the file:
- sudo nano /etc/php/8.x/apache2/php.ini
Replace 8.x with your installed PHP version.
Optimize Memory Limits
Locate:
- memory_limit = 128M
Recommended:
- memory_limit = 256M
Adjust Script Execution Time
Locate:
- max_execution_time = 30
Recommended:
- max_execution_time = 120
Enable and Tune OPcache
One of the most important PHP optimizations is OPcache.
Verify that it’s enabled:
- php -i | grep opcache.enable
Expected:
- opcache. enable => On
Open the OPcache configuration:
- sudo nano /etc/php/8.x/mods-available/opcache.ini
Add or adjust:
- opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=1
opcache.revalidate_freq=60
Restart Apache and PHP
After making configuration changes, restart the relevant services.
- sudo systemctl restart apache2
If PHP-FPM is installed:
- sudo systemctl restart php8.3-fpm
Adjust the version number if necessary.
Verify there are no errors:
- sudo systemctl status apache2
- sudo systemctl status php8.3-fpm
Both services should show:
- active (running)
Step 7: Create a Test Database and User
Before deploying applications, create a dedicated database and user account. Connect to MariaDB:
- sudo mysql
Create a database:
- CREATE DATABASE website_db;
Create a user:
- CREATE USER ‘website_user’@’localhost’ IDENTIFIED BY ‘StrongPasswordHere’;
Grant permissions:
- GRANT ALL PRIVILEGES ON website_db.* TO ‘website_user’@’localhost’;
Apply changes:
- FLUSH PRIVILEGES;
Exit:
- EXIT;
Verify Database Connectivity
Test authentication using the newly created account:
- mysql -u website_user -p
Enter the password.
If login succeeds, test database access:
- SHOW DATABASES;
You should see:
- website_db
Exit:
- EXIT;
Step 8: Configure Apache Virtual Hosts
Although Apache automatically serves content from /var/www/html, relying on the default website isn’t recommended for production environments.
Instead, each website should have its own Virtual Host, allowing you to isolate configurations, simplify maintenance, and host multiple domains on the same server without modifying Apache’s global configuration.
Even if you currently plan to host only a single website, using Virtual Hosts from the beginning makes future expansion significantly easier.
Create the Website Directory
For this guide, we’ll use nexonserver.com as our domain.
Create the directory structure:
- sudo mkdir -p /var/www/nexonserver.com/public_html
Assign ownership to Apache’s web user:
- sudo chown -R www-data:www-data /var/www/nexonserver.com Set appropriate permissions:
- sudo find /var/www/nexonserver.com -type d -exec chmod 755 {} \; sudo find /var/www/nexonserver.com -type f -exec chmod 644 {} \;
Why These Permissions?
One of the most common mistakes is assigning overly permissive permissions such as: • chmod -R 777
This should never be used on a production server.
Granting write access to every user significantly increases the risk of unauthorized file modifications if the server is compromised.
Using 755for directories and 644 for files follows Linux security best practices while allowing Apache to serve content correctly.
Create a Test Page
Before configuring Apache, create a simple HTML file to verify the Virtual Host later. sudo nano /var/www/nexonserver.com/public_html/index.html Add:
<!DOCTYPE html>
<html>
<head>
<title>Apache Virtual Host</title>
</head>
<body>
<h1>Apache Virtual Host is Working!</h1>
</body>
</html>
Save the file.
Create a Virtual Host Configuration
Apache stores Virtual Host configurations inside:
/etc/apache2/sites-available/
Create a new configuration file.
sudo nano /etc/apache2/sites-available/nexonserver.com.conf Insert the following configuration:
<VirtualHost *:80> ServerAdmin [email protected]
ServerName nexonserver.com ServerAlias www.nexonserver.com
DocumentRoot /var/www/nexonserver.com/public_html <Directory /var/www/nexonserver.com/public_html>
Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory>
ErrorLog ${APACHE_LOG_DIR}/ nexonserver.com-error.log CustomLog ${APACHE_LOG_DIR}/ nexonserver.com -access.log combined
</VirtualHost>
Save the file.
Understanding Directive
Rather than blindly copying the configuration, it’s useful to understand what each directive controls.
Enable the Website
Enable the new Virtual Host.
- sudo a2ensite nexonserver.comom.conf
Disable the default Apache website.
- sudo a2dissite 000-default.conf
This prevents Apache from accidentally serving the default page.
Enable Required Apache Modules
Several Apache modules are essential for modern websites.
Enable them now.
- sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo a2enmod deflate
sudo a2enmod ssl
sudo a2enmod http2
Let’s briefly explain why each one matters.
| Module | Purpose |
| rewrite | Enables clean URLs and SEO-friendly routing. |
| headers | Allows security and caching headers. |
| expires | Browser caching configuration. |
| deflate | Gzip compression. |
| ssl | HTTPS support. |
| http2 | Improved HTTP performance over HTTPS. |
Nearly every modern PHP application benefits from these modules.
Validate the Configuration
Before restarting Apache, always validate the configuration. • sudo apache2ctl configtest
Expected output:
- Syntax OK
If Apache reports an error, fix it before restarting the service. This simple habit can prevent accidental downtime.
Test the Virtual Host
If your DNS already points to the server, simply visit: http://nexonserver.comom
Otherwise, temporarily modify your local hosts file to point the domain to your server’s IP address for testing.
You should now see the page created earlier:
- Apache Virtual Host is Working!
If Apache still displays the default Ubuntu page, check the following:
- The Virtual Host has been enabled with a2ensite.
- The default site has been disabled using a2dissite.
- ServerName matches the requested domain.
- DNS (or your hosts file) points to the correct server.
- Apache was reloaded after the configuration changes.
Virtual Hosts let each domain use its own document root, logs, SSL certificate, and configuration.
Step 9: Secure Your Website with Let’s Encrypt SSL
Install Certbot and the Apache plugin:
- sudo apt install certbot python3-certbot-apache -y
Before requesting a certificate, ensure:
- Your domain points to the server’s public IP address.
- Port 80 is reachable from the internet.
- Apache is serving the correct Virtual Host.
Request a certificate:
- sudo certbot –apache
Certbot will detect your Virtual Hosts and guide you through the configuration process.
During the setup, you’ll be asked whether HTTP traffic should automatically redirect to HTTPS.
Choose:
- Redirect
Certbot will update your Apache configuration automatically.
Verify Automatic Renewal
Let’s Encrypt certificates are valid for 90 days, but Certbot installs a system timer that renews them automatically.
Verify the renewal timer:
- systemctl list-timers | grep certbot
You can also perform a dry run:
- sudo certbot renew –dry-run
If no errors are reported, certificate renewal is correctly configured.
Step 10: Enable HTTP Security Headers
SSL encrypts traffic, but browsers also rely on HTTP response headers to enforce additional security policies.
Apache makes it easy to add these protections.
Open your Virtual Host configuration:
- sudo nano /etc/apache2/sites-available/nexonserver.comom.conf
Inside the <VirtualHost> block, add:
- Header always set X-Frame-Options “SAMEORIGIN”
Header always set X-Content-Type-Options “nosniff” Header always set Referrer-Policy “strict-origin-when cross-origin”
Header always set X-XSS-Protection “1; mode=block” Header always set Permissions-Policy “geolocation=(), microphone=(), camera=()”
Step 11: Improve Apache Performance
Apache performs well out of the box, but a few adjustments can noticeably improve responsiveness under heavier workloads.
Open the main configuration:
sudo nano /etc/apache2/apache2.conf
Secure Your Server Fast
Linux VPS
Step 12 – Test PHP Processing
Create a PHP test page.
- sudo nano /var/www/nexonserver.comom/public_html/info.php Insert:
<?php
phpinfo();
?>
Visit:
https://nexonserver.comom/info.php
If PHP is configured correctly, you’ll see a page displaying detailed information about your PHP installation.
Remove the Test Page
Although phpinfo() is extremely useful during deployment, it also exposes valuable information to attackers, including:
• Installed PHP version
• Enabled modules
• Loaded extensions
• Environment variables
• Server paths
Once you’ve confirmed PHP is working, remove the file immediately.
- sudo rm /var/www/nexonserver.comom/public_html/info.php Leaving this file accessible on a production server is considered poor security practice.
Final Verification Checklist
Before deploying applications, verify that your server meets the following requirements:
- Ubuntu fully updated
- Apache running without configuration errors
- UFW enabled
- HTTP and HTTPS accessible
- MariaDB secured
- Dedicated database users created
- PHP installed with required extensions
- OPcache enabled
- Virtual Hosts configured
- SSL certificate installed
- HTTP redirected to HTTPS
- Security headers enabled
- Browser caching configured
- Compression enabled
- phpinfo() removed
Completing this checklist ensures your server is ready to host production workloads.
Common Troubleshooting Tips
Even experienced administrators occasionally encounter issues during deployment. Here are some of the most common problems and their solutions.
Apache won’t start
Validate the configuration:
- sudo apache2ctl configtest
Then inspect the logs:
- sudo journalctl -u apache2 –no-pager
PHP files download instead of executing
This usually indicates that Apache isn’t processing PHP correctly.
Verify:
- PHP is installed.
- PHP-FPM is running (if used).
- Required Apache modules are enabled.
Database connection errors
Check:
- Database credentials
- User permissions
- Database name
- MariaDB service status
403 Forbidden
Most permission issues result from incorrect ownership or file permissions. Verify:
- sudo chown -R www-data:www-data /var/www/nexonserver.comom
Conclusion: How to Install LAMP Stack Ubuntu the Right Way
A properly configured LAMP stack provides a stable, secure, and highly compatible platform for hosting PHP applications. While installing Apache, MariaDB, and PHP only takes a few minutes, transforming that installation into a production-ready environment requires careful attention to security, performance, and long-term maintainability.
By following the steps in this guide, you’ve built a solid foundation that includes firewall protection, a hardened database server, optimized PHP settings, Virtual Hosts, HTTPS encryption, browser security headers, compression, and caching. These best practices not only improve reliability but also make future maintenance and scaling significantly easier.
Whether you’re deploying a WordPress blog, an OpenCart store, a Laravel application, or a custom PHP project, this setup provides a dependable starting point that can grow with your infrastructure.


