
Understanding the LAMP stack VPS setup will help you create a solid, secure site. This technology offers support, security, and all you need to launch functional web applications.
This blog post discusses the steps to set up a secure LAMP stack on a Linux VPS hosting. It’ll also highlight basic and advanced security measures with overall performance tips.
A secure LAMP stack depends heavily on the stability and configuration flexibility of your VPS hosting. The comparison table below highlights Linux VPS providers that offer reliable performance, full root access, and strong security controls. Explore our recommended VPS hosting options.
Linux VPS Hosting Providers Optimized for Secure LAMP Deployments
| Provider | User Rating | Recommended For | |
|---|---|---|---|
![]() | 4.8 | Scalability | Visit Kamatera |
![]() | 4.6 | Affordability | Visit Hostinger |
![]() | 4.7 | Developers | Visit IONOS |
Understanding the Importance of the LAMP Stack for Modern Web Development
The LAMP stack dates back to the late 90s. Despite its age, it’s still valuable for modern web development. It includes a set of open-source software that has served developers even before LAMP became a thing.
For instance, Apache was developed in 1995 and is still one of the popular server choices today. Also, 72.4% of websites use PHP as their scripting language.
Developers still trust this technology for its consistency and support. The four components: Linux, Apache, MySQL, and PHP work together to support dynamic web applications. You can build and host dynamic websites and custom APIs on this framework.
Here’s how it works:
- Linux: The operating system that forms the base. It’s secure and stable, running the web server and database.
- Apache: The web server that receives requests and serves content to visitors.
- MySQL (or its fork MariaDB): This component manages your database, storing and retrieving data.
- PHP: The server-side scripting language that brings all elements together. It processes dynamic requests to create real-time content.
Major platforms like WordPress, Laravel, and Magento use LAMP.

Moreover, it’s open-source and free to use. This advantage lets you modify components as you wish while saving costs. You’re also assured of ongoing support from experienced developers if you encounter any problems. LAMP is perfect for projects that require continuous uptime.
Initial Server Setup and OS Optimization
How good your security is will determine how far you’ll go. An insecure LAMP stack VPS setup leaves room for attacks. But a secure configuration guarantees long-term success.
Before you install any application, secure your server. Once you log in, create a non-root user with sudo privileges to run most activities. Linux VPSs come with a default “root” user that can perform any action, including destructive ones.
Bad actors can easily obtain the root password to gain complete control of your account.
Next, disable root login via SSH. Edit your SSH configuration to stop direct root access. This step will push all administrative tasks through your sudo-enabled user account.
Package management comes next. Run sudo apt update on Ubuntu systems to refresh package lists. Amazon Linux 2 users should execute sudo yum update -y instead. These commands install the latest versions with up-to-date security patches.
Automation saves time and lowers risks. Enable unattended-upgrades on Ubuntu to automatically handle security updates. Set it up in /etc/apt/apt.conf.d/50unattended-upgrades to specify which updates install automatically.
Amazon Linux 2 requires additional firewall configuration through AWS security groups. Open ports 22 (SSH), 80 (HTTP), and 443 (HTTPS) before proceeding. Without these rules, you won’t be able to access your web server after installation.

Step 1: How to Install Apache Web Server
Apache remains a trusted web server, even with other alternatives available. It’s flexible and can turn your server into a working web platform.
For Ubuntu users, use this instruction:
sudo apt install apache2
This simple command line installs the full Apache web server. You automatically get all the required dependencies for basic tasks.
Amazon Linux 2 uses the following command:
sudo yum install -y httpd
sudo systemctl enable httpd
The first instruction installs Apache (called httpd on Red Hat-based systems). The second enables Apache to run on its own after server reboots.
Your web server stores files in specific locations. The document root typically lives at /var/www/html or /var/www/your_domain. Understanding this file path is key when deploying websites.
After the installation process, check if Apache is active:
Open your web browser and visit your server’s public IP address. You should see Apache’s default page, which confirms it’s successfully installed.
If you don’t see the page, check your firewall rules and ensure Apache is running using sudo systemctl status apache2.
Configuring Firewall Rules for a Secure Linux VPS

A firewall is like a traffic warden. It controls network traffic coming in and out of your server, blocking harmful actors from accessing your network.
Ubuntu’s UFW (Uncomplicated Firewall) simplifies this process.
Enable Apache access with:
sudo ufw allow in “Apache Full”
Apache Full opens port 80 for standard HTTP and port 443 for encrypted HTTPS.
Each port has its roles:
- Port 22 is for SSH, letting you manage your server remotely.
- Port 80 handles regular, unencrypted web traffic.
- Port 443 delivers HTTPS traffic, protecting data with SSL/TLS encryption.
Understanding their role will help with management.
Monitor your firewall configuration with this command:
sudo ufw status
This command shows all active rules and their current status. Check it often to ensure no unauthorized ports are open.
Amazon Linux 2 users manage ports through AWS security groups. Use the AWS Console to add or remove rules. Remember, only open ports you need.
Best Practices to Configure Apache for Production

Apache’s default setup provides a good starting point for developers. However, it’s risky because it reveals helpful information to hackers. Editing the standard configuration will improve security.
Hide server details. Create a custom configuration file at /etc/apache2/conf-available/custom.conf and add these directives:
ServerTokens Prod
ServerSignature Off
This step prevents the Apache version number and operating system type from appearing in HTTP headers and error pages.
Security headers provide additional protection. Disable TraceEnable to prevent cross-site tracking attacks. Unset the X-Powered-By header to avoid revealing your PHP version. These changes limit the information attackers can see.
Protect the directory to stop unauthorized browsing. Add Options all -Indexes to your setting. This command disables directory browser listing to protect sensitive data. Users won’t be able to see files and subdirectories without permission.
Ensure it’s configured properly:
sudo a2enmod headers
sudo systemctl restart apache2
The first command activates Apache’s headers. The second restarts Apache to apply all changes.
Setting Up Apache Virtual Hosts for Your Domain
The virtual host feature allows your VPS to host multiple sites. Each site has its own documentation root and settings to prevent issues from spreading. Setting up this feature in Apache helps manage resources and makes scaling easier.
Set directory permissions:
sudo chown -R $USER:$USER /var/www/your_domain
This command lets the web server read site files safely. Wrong permissions cause errors or risks.
Create a different configuration file for each domain you host. Configuration files live in /etc/apache2/sites-available/. Edit them with sudo nano. Specify the ServerName (your domain) and DocumentRoot (where files are stored) within each configuration.
Activation requires two steps:
sudo a2ensite your_domain
apache2ctl configtest
The first command enables your new virtual host. The second checks for syntax errors before restarting Apache. Run configtest before reloading to avoid breaking the web server.
Step 2: How to Install MySQL and Secure Your Database

MySQL server keeps and manages your website data. After installing Apache, this component is the next on the LAMP stack.
Ubuntu users follow this command:
sudo apt install mysql-server
The package manager installs the MySQL database system with all dependencies, ready to configure.
Amazon Linux 2 users should consider MariaDB instead:
sudo amazon-linux-extras install mariadb10.5
MariaDB is now a preferred choice over MySQL for its better performance.
Secure MySQL installation immediately with these instructions:
sudo mysql_secure_installation
This security script helps you safeguard your database server. You’ll set a root account password, remove anonymous users, disallow root login remotely, and remove test database.
The validate password plugin offers three security levels to test passwords:
- 0 (LOW): Accepts any password length
- 1 (MEDIUM): Requires at least eight characters with mixed case, numbers, and symbols
- 2 (STRONG): Adds dictionary checks to prevent common passwords
Choose based on your security requirements. Production environments often require MEDIUM or STRONG password validation.
Advanced Database Management and MySQL Hardening

Don’t stop at basic installation and security. Without advanced protection, your database will be prone to attacks.
Prevent unauthorized remote access by editing your MySQL configuration. This approach is the first step in preventing unauthorized MySQL connections. Edit mysqld.cnf and set the bind-address to 127.0.0.1 to permit connections only from the local server.
Isolate users to prevent attackers from accessing other applications:
GRANT ALL ON database_name.* TO ‘username’@’localhost‘;
Create separate database users for each application. Never share the MySQL root user across multiple applications. This step prevents attackers from accessing other databases in case of a breach.
File upload security requires attention:
Add local-infile=0 to the [mysqld] section of your configuration. This addition blocks anyone from uploading harmful files through the database.
PHP 8 may need code adjustment. Modern MySQL versions use caching_sha2_password authentication. Older PHP applications may need users configured with mysql_native_password instead. Monitor your error logs if database connections fail after upgrading.
Step 3: Installing PHP and Essential Modules

PHP index is the final layer of the LAMP stack. It’s the scripting language that generates dynamic web content.
Ubuntu 22.04 comes with PHP 8.1.2. Install it with:
sudo apt install php libapache2-mod-php
Amazon Linux 2 supports PHP 8.2 through amazon-linux-extras. This newer version runs faster and is more secure.
Essential PHP modules add extra features:
sudo apt install php-mysql php-curl php-mbstring
php-mysql handles database communication, php-curl manages HTTP requests, while php-mbstring handles multibyte string processing. Most applications require all three to function well.
Verify if the PHP installation works well:
Create a file called info.php in your document root containing:
<?php phpinfo(); ?>
Access it through your browser at http://your_ip/info.php. You’ll see a detailed page showing your PHP configuration, installed modules, and system information.
Finding additional modules is straightforward:
apt search php-
This command lists all available PHP extensions. Common additions include php-xml for XML processing and php-zip for archive handling.
PHP Security: Hardening php.ini for Production

Just as with other default installations, PHP configuration focuses more on ease of use. This setup leaves you to harden security on your own.
Data leak gives hackers an advantage. Edit your php.ini file and set:
expose_php = Off
display_errors = Off
These edits hide PHP’s version and prevent error messages from exposing file paths or code details.
Restricting functions stops risky actions:
Use the disable_functions directive to prevent PHP from executing system commands. Add shell_exec, passthru, system, and similar functions to this list. Legitimate applications rarely need direct system access.
Resource limits prevent denial-of-service attacks:
max_execution_time = 30
memory_limit = 40M
upload_max_filesize = 1M
These settings prevent harmful PHP scripts from overwhelming the server. Start with low limits and adjust as needed.
Restrict access to the file system for extra protection:
Configure open_basedir to limit PHP’s file access to your web directories only. This step prevents scripts from reading sensitive system files even if other security measures fail.
Summary of LAMP Installation Commands by Distribution
Below are different distributions with their commands for installing LAMP:
Component | Ubuntu (22.04 LTS) | Amazon Linux 2 (AL2) |
| System Update | sudo apt update | sudo yum update -y |
| Install Apache | sudo apt install apache2 | sudo yum install -y httpd |
| Install Database | sudo apt install mysql-server | sudo yum install mariadb-server |
| Install PHP | sudo apt install php libapache2-mod-php | amazon-linux-extras install php8.2 |
| Firewall Tool | UFW (Uncomplicated Firewall) | Security Groups (AWS Console) |
You’ll find this information helpful when working across multiple server environments.
The apt install command and the yum commands do the same thing with different package managers. Knowing both boosts your admin skills.
Testing Your Linux Apache MySQL PHP Stack Integration

Your job doesn’t end at installing the LAMP stack. Test your configuration to catch and fix problems on time.
Test your PHP scripting language database connection first. Create a test file that attempts a MySQL connection using PDO (PHP Data Objects). If it works, it means your stack communicates well.
Test database directly:
sudo mysql
CREATE DATABASE example_database;
CREATE TABLE example_database.todo_list (item_id INT AUTO_INCREMENT, content VARCHAR(255), PRIMARY KEY(item_id));
This approach creates a test database and table structure. Insert a few records, then retrieve them through a PHP script. Successful read and write operations confirm that permissions are correct.
Cleanup after testing to protect your server:
Delete any info.php files after testing. These files disclose server details that hackers are often after.
Monitor your log to catch problems early:
sudo tail -f /var/log/apache2/error.log
Watch this file during testing. It displays processing errors so that you can fix issues before production.
Adding Extra Layers: Fail2ban and ModSecurity
You need to go the extra mile to secure your servers exposed to the internet.
Fail2ban monitors system logs and blocks suspicious server IP addresses. Install it with sudo apt install fail2ban. This software protects against brute force, DoS, and DDoS attacks.
Configuration makes SSH more secure first:
Set up rules that ban IPs after five failed login attempts within ten minutes. Make the ban last at least one hour to stop brute-force attacks.
ModSecurity acts as a web application firewall. Install it with:
sudo apt install libapache2-mod-security2
Pair it with the OWASP Core Rule Set. This combination protects against SQL injection, cross-site scripting, and other common web attacks.
ModEvasive handles DoS protection:
sudo apt install libapache2-mod-evasive
Configure DOSPageCount to 5 requests and DOSBlockingPeriod to 600 seconds. This setting blocks clients from sending too many requests without affecting regular traffic.
Taking these extra steps will make it difficult for hackers to break into your server.
Managing Your Linux VPS with phpMyAdmin
Command-line database management works but isn’t always simple.
phpMyAdmin helps you manage multiple databases. It provides a web-based interface for managing MySQL and MariaDB database servers. Download the latest version from the official site and extract it into a subdirectory under/var/www/html.
Don’t skip the security steps:
Never run phpMyAdmin without HTTPS encryption. Hackers can easily steal database passwords sent over plain HTTP. Use Let’s Encrypt for free SSL certificates to manage cost.

Restrict access for extra protection:
Configure .htaccess basic authentication for the phpMyAdmin directory. Alternatively, use IP whitelisting to allow access only from trusted addresses. Both methods reduce unauthorized access attempts.
Custom aliases improve security by making things less obvious:
Configure Apache to serve phpMyAdmin from a non-standard URL. Instead of the predictable /phpmyadmin path, use something unique like /secure-db-admin-panel. Automated scanners won’t find it as easily.
Remember that attackers have targeted phpMyAdmin. Thus, update it often to stay prepared. Remove it if you’re okay with using the command line.
Selecting the Best Linux VPS for Your Business Growth
Choosing the right VPS hosting platform matters. Your choice will impact your hosting and your business.
Ubuntu 22.04 LTS is a good choice. It gets security updates until 2032, giving you 10 years of support without forced upgrades. It’s ideal for long-term projects.
Your Linux VPS must provide your own CPU and memory to process dynamic content. Shared resources slow down PHP and frustrate users, hurting your search rankings.
Look for providers offering vertical scaling options. The best VPS hosting providers will help you scale efficiently to handle increased traffic. You only need to add resources to keep your site running continuously.
For high-scale B2B needs, consider containerized solutions. Docker on Ubuntu offers isolation, and managed databases reduce maintenance. It’s perfect for when your project needs advanced features.
Learn the difference between managed and unmanaged VPS. Managed hosting means the provider handles server setup and maintenance. Unmanaged hosting gives you full control but requires you to configure everything, as we’ve shown you in this article. Choose based on your skills and budget.
Building a Website for Your Online Presence
Create a website to make it easy for people to find you and your business.
Start with a website builder if you’re a beginner. Hostinger or IONOS are a good choice for getting started immediately. They offer simple templates with a drag-and-drop interface to simplify setup. Don’t forget to use the best web hosting service for speed and security.
Conclusion
To achieve a secure LAMP stack VPS setup is not rocket science. This comprehensive guide has all you need to get started.
Remember, VPS security is an ongoing process. Follow the security tips in this article to secure your server and site. Perform regular updates, monitor your log, and adjust settings to meet growing needs.
Next Steps: What Now?
Ready to set up your LAMP stack on Linux VPS? Do the following:
- Choose the best Linux VPS based on your skill and budget.
- Secure your server before any installation.
- After installing each component, perform security hardening.
- Test the final installation before deployment.
- Perform ongoing maintenance and security checks.
Further Reading & Useful Resources
Below are additional resources to help you learn more about VPS and hosting:
- Types of VPS: Learn the different types and choose the one that’s best for you.
- VPS vs Dedicated Server: Which is best for you?
- What is Windows VPS? Understand Windows virtual private server.
- Types of hosting: Learn the difference between shared, VPS, and dedicated.
- What is cloud hosting? Understand how cloud hosting works.





