Install PHP & Apache on Linux — A Fast, Step-by-Step Setup Guide
Getting a reliable web stack running on your Linux VPS doesnt have to be painful. This fast, step-by-step guide shows you how to install Apache and PHP on common distributions, with practical configuration tips for performance, security, and maintainability.
Setting up a reliable web stack on a Linux VPS is a fundamental task for webmasters, developers, and businesses that need to host PHP-based applications. This guide walks you through a fast, step-by-step process to install and configure Apache and PHP on common Linux distributions, explains the underlying principles, discusses application scenarios, compares deployment options, and offers practical recommendations for choosing VPS resources. The instructions and configuration tips are focused on real-world production needs: performance, security, and maintainability.
Understanding the components and how they interact
Before diving into commands, it helps to understand the roles of the main components:
- Apache HTTP Server: a mature, flexible web server that serves static files and routes requests to dynamic handlers. Apache supports multiple processing models (prefork, worker, event) and integrates with PHP either via embedded modules or through FastCGI.
- PHP: the server-side scripting language that powers many CMS platforms (WordPress, Drupal, Joomla) and custom web apps. PHP can be executed as an Apache module (mod_php) or via PHP-FPM (FastCGI Process Manager).
- PHP extensions and opcache: extensions (e.g., mysqli, pdo_mysql, gd) are required by applications. Opcache dramatically improves PHP performance by caching compiled script bytecode.
- Process managers and integration: mod_php runs PHP inside Apache worker processes, while PHP-FPM runs PHP in separate processes and communicates via FastCGI—typically recommended for better isolation and scalability.
Which deployment to choose: mod_php vs PHP-FPM
Selecting the right integration affects performance, memory usage, and security:
- mod_php
- Simpler to set up (PHP built as an Apache module).
- Each Apache process runs PHP; this increases memory usage for high-concurrency workloads.
- Less isolation between virtual hosts and processes.
- PHP-FPM (recommended)
- Runs PHP in separate worker pools, offering better resource isolation and control.
- Supports graceful process management and adaptive process spawning.
- Works well with Apache’s event MPM via mod_proxy_fcgi, delivering higher concurrency.
Preparation: choose your Linux distro and update the system
This guide covers the two most common families: Debian/Ubuntu and RHEL/CentOS/Alma/Rocky systems. Always start by updating package metadata and the system packages to ensure security patches are applied.
Common preparatory steps
- Log in as a privileged user or use sudo.
- Set the system clock and timezone accurately, or configure NTP/chrony.
- Open SSH and firewall (ufw or firewalld) ports for administration and HTTP (80) / HTTPS (443).
Step-by-step installation
The following are concise, distribution-specific steps. Replace placeholder package manager commands as needed.
Debian / Ubuntu (APT)
1. Update packages:
sudo apt update && sudo apt upgrade -y
2. Install Apache and PHP-FPM (recommended):
sudo apt install -y apache2 php-fpm libapache2-mod-fcgid
3. Install common PHP extensions used by web apps:
sudo apt install -y php-mysql php-xml php-mbstring php-gd php-curl php-zip php-intl
4. Enable required Apache modules and configure proxying to PHP-FPM:
sudo a2enmod proxy_fcgi setenvif
Enable the mpm_event module (for high concurrency) and disable prefork if mod_php was active:
sudo a2dismod mpm_prefork && sudo a2enmod mpm_event
5. Configure a VirtualHost to pass .php files to the PHP-FPM socket or TCP port. Place configuration under /etc/apache2/sites-available/ and enable with a2ensite.
6. Restart services:
sudo systemctl restart php*-fpm && sudo systemctl restart apache2
RHEL / CentOS / Alma / Rocky (YUM/DNF)
1. Update system:
sudo dnf update -y
2. Install Apache (httpd) and PHP-FPM:
sudo dnf install -y httpd php-fpm
3. Install extensions:
sudo dnf install -y php-mysqlnd php-xml php-mbstring php-gd php-curl php-zip
4. Configure Apache to proxy to PHP-FPM. On these systems, enable and start services:
sudo systemctl enable –now php-fpm httpd
5. Adjust SELinux boolean if enabled to allow Apache to connect to network or PHP-FPM sockets:
sudo setsebool -P httpd_can_network_connect 1
Configuring virtual hosts and directory security
Use separate virtual host files per site to isolate settings and optimize caching rules. Key considerations:
- Set DocumentRoot and define Directory directives with controlled Options and AllowOverride settings (avoid excessive use of AllowOverride unless you need .htaccess).
- Enable HTTP to HTTPS redirects and HSTS headers for secure production environments.
- Limit access to sensitive files (wp-config.php, .env) via Require all denied or rewrite rules.
Performance tuning
Out-of-the-box installations are functional but not optimized. Practical tunables include:
- PHP-FPM pool configuration (www.conf): tune pm = dynamic/static, pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers based on available RAM and expected concurrency.
- Opcache: enable and configure opcache.memory_consumption, opcache.max_accelerated_files, and opcache.validate_timestamps for production (set validate_timestamps=0 and use deployments that purge opcache on release).
- Apache MPM: use mpm_event with PHP-FPM; configure MaxRequestWorkers and ServerLimit to avoid oversubscription.
- Use a reverse proxy or CDN for static assets to reduce origin load.
Security hardening
Secure configuration is essential for production VPSes:
- Run regular package updates and enable automatic security updates where possible.
- Use HTTPS with certificates from Let’s Encrypt or enterprise CAs. Automate renewal via certbot.
- Isolate applications: use separate system users, chroot or containers, and restrict file permissions (files 640, directories 750) with appropriate ownership.
- Harden PHP settings in php.ini: disable dangerous functions (exec, system, passthru), limit memory_limit and max_execution_time, and enable error logging but disable display_errors in production.
- Configure fail2ban and web application firewalls (ModSecurity) for additional protection against common attacks.
Testing and validation
After installation and configuration, validate the stack:
- Create a test PHP info page (phpinfo()) in the web root and access it via browser to confirm PHP is processed by Apache and the expected PHP-FPM or module is in use.
- Use Apache and PHP logs for troubleshooting: /var/log/apache2/ or /var/log/httpd/ and /var/log/php-fpm/.
- Run load tests or use benchmarking tools (ab, wrk) in a controlled environment to measure throughput and latency, then adjust PHP-FPM and Apache MPM settings accordingly.
Application scenarios and recommended setups
Choose configurations depending on the workload:
- Small business or low-traffic sites: A single VPS with Apache + PHP-FPM, modest resource allocation (1–2 vCPU, 1–2 GB RAM), and a lightweight caching plugin or reverse-proxy is sufficient.
- Medium traffic or multiple sites: Increase vCPU/RAM, use opcode caching, tune PHP-FPM pools per site, and consider Nginx as a front-end reverse proxy for static content.
- High-traffic or enterprise apps: Use horizontally scalable architecture—load balancers, multiple application servers, object caching (Redis/Memcached), and a managed database. Keep web servers stateless and store uploads in object storage.
Choosing the right VPS and operational recommendations
When selecting a VPS for PHP + Apache hosting, consider:
- CPU and clock speed: PHP is CPU-bound during script execution; higher clock speeds improve single-request latency.
- Memory: allocate enough RAM for PHP-FPM pools and Apache processes; insufficient RAM leads to swap and severe performance degradation.
- Storage: use SSD-backed disks for fast I/O. For high I/O workloads, consider NVMe or provisioned IOPS.
- Network: low-latency, high-bandwidth network interconnects matter for user experience and external API calls.
- Backup and snapshot options: ensure automated backups and recovery procedures exist.
For many site owners and agencies, a reliable provider like VPS.DO offers flexible configurations. If you’re targeting U.S. audiences, you may evaluate their USA VPS plans for location-sensitive latency and compliance requirements.
Summary
Installing Apache and PHP on Linux is straightforward, but building a production-ready stack requires careful choices around integration (mod_php vs PHP-FPM), performance tuning (PHP-FPM pools, opcache, Apache MPM), and security hardening. Start with a minimal, secure baseline, enable opcache, tune process managers to match VPS resource limits, and monitor application metrics under realistic load. For site owners and developers looking to host PHP applications, pick a VPS that balances CPU, memory, and storage for your expected traffic, and ensure backups and security policies are in place.
If you plan to deploy multiple or business-critical sites, evaluate providers that offer scalable VPS plans and U.S.-based nodes if your user base is primarily in North America. For more information on infrastructure options, check out VPS.DO and their USA VPS offering to compare plans and network locations.