Install PHP and Apache on Linux Servers — A Fast, Step-by-Step Guide
Want to host PHP sites on your VPS without the guesswork? This fast, step-by-step guide shows how to install PHP and Apache on Linux servers, explains choices like mod_php vs PHP-FPM, and gets you production-ready with simple, practical commands.
Deploying PHP and Apache on a Linux VPS is a foundational task for webmasters, developers, and businesses running PHP-based applications. Whether you are setting up a new WordPress site, a custom PHP application, or a legacy system, a well-configured Apache + PHP stack ensures reliability, security, and performance. This guide walks you through practical steps, explains underlying principles, compares common options, and offers advice for production deployments on VPS environments.
How Apache and PHP Work Together: Key Principles
Apache is a modular HTTP server. PHP can be executed in several ways within Apache: as an embedded module (mod_php) or via a separate process manager (PHP-FPM) connected through FastCGI. Each approach affects concurrency, memory usage, and compatibility with Apache’s MPM (Multi-Processing Module).
- mod_php: PHP runs inside Apache worker processes. Simpler to set up, but ties PHP to the webserver process model — typically requires prefork MPM (process-based), which uses more memory and is less scalable for high-concurrency scenarios.
- PHP-FPM (FastCGI Process Manager): PHP runs in dedicated worker processes outside Apache. Apache communicates via mod_proxy_fcgi or mod_fastcgi. Compatible with event or worker MPMs and generally more efficient for dynamic workloads.
- MPM choices: On modern servers, event MPM is preferred for static content and high concurrent connections; combine it with PHP-FPM for best performance.
When to Use This Stack: Typical Use Cases
This stack is suitable for a wide range of applications:
- Content management systems: WordPress, Drupal, Joomla.
- Custom PHP applications and frameworks: Laravel, Symfony, CodeIgniter.
- Legacy applications that depend on Apache-specific modules (.htaccess, mod_rewrite).
- Environments requiring fine-grained per-site Apache configuration (VirtualHost + .htaccess).
Step-by-Step Installation on Popular Linux Distributions
Debian / Ubuntu
1) Update package lists: sudo apt update.
2) Install Apache and PHP-FPM (recommended): sudo apt install apache2 php-fpm. For a specific PHP version (e.g., 8.1): sudo apt install php8.1-fpm.
3) Enable required Apache modules and proxy the PHP-FPM socket: sudo a2enmod proxy_fcgi setenvif and sudo a2enconf php8.1-fpm (replace version as needed), then sudo systemctl restart apache2.
4) Verify PHP-FPM is running: systemctl status php8.1-fpm. Create a test file in /var/www/html/info.php with <?php phpinfo(); ?> and visit http://server-ip/info.php.
CentOS / RHEL / Rocky Linux
1) Update packages: sudo yum update (or dnf on newer systems).
2) Install Apache and PHP-FPM: sudo yum install httpd php-fpm. For specific versions, consider Remi repository.
3) Configure Apache to use proxy_fcgi: enable modules and add a VirtualHost that proxies .php to the FPM socket or TCP port. Example VirtualHost snippet: ProxyPassMatch "^/(..php(/.)?)$" "unix:/run/php-fpm/www.sock|fcgi://localhost/".
4) Start and enable services: sudo systemctl enable –now httpd php-fpm. Protect the phpinfo page and verify operation.
Configuration Essentials and Tuning
PHP-FPM Pools
PHP-FPM uses pools defined in /etc/php/8.1/fpm/pool.d/*.conf (path varies by distro). Important settings:
- pm: dynamic, static, or ondemand. Use dynamic for predictable traffic, ondemand for spiky workloads.
- pm.max_children: maximum PHP worker processes — controls memory usage. Calculate by dividing available PHP memory by average process size.
- pm.start_servers, pm.min_spare_servers, pm.max_spare_servers: tune when using dynamic.
Example approach: if each PHP-FPM process uses ~40MB and you have 2GB RAM with 1GB reserved for OS and other services, set pm.max_children ≈ 25.
php.ini Important Settings
- memory_limit: set per-application needs (e.g., 128M–512M).
- upload_max_filesize and post_max_size: raise for large uploads.
- max_execution_time: keep reasonable to avoid runaway scripts.
- display_errors: set to Off in production; log_errors On.
- expose_php: set to Off to avoid revealing PHP version in headers.
Apache MPM and Worker Model
For Apache in combination with PHP-FPM, use the event MPM (or worker) to maximize concurrency for static requests. On Debian/Ubuntu: sudo a2dismod mpm_prefork; sudo a2enmod mpm_event, then restart Apache. Avoid mod_php if you need event MPM.
Opcache and PHP Performance
Enable and tune Opcache to reduce PHP compile time. Typical php.ini settings:
- opcache.enable=1
- opcache.memory_consumption=128
- opcache.max_accelerated_files=10000
- opcache.validate_timestamps=1 (set to 0 in immutable production environments)
Opcache dramatically improves performance for repeated requests by caching precompiled bytecode in shared memory.
Security Best Practices
Security on a public-facing VPS must be layered:
- Least privilege: run PHP-FPM pools under separate system users per site when hosting multiple customers.
- File permissions: web files typically owned by a deploy user, readable by the PHP-FPM user, with uploads writable only where necessary (e.g., 750/640).
- Disable unnecessary PHP functions: disable_functions in php.ini for functions like exec, shell_exec where not needed.
- Web application firewall: deploy mod_security with OWASP CRS to mitigate common attacks.
- HTTPS: always use TLS — obtain certificates via Let’s Encrypt and configure automated renewal (certbot).
- Firewall: use UFW, firewalld, or iptables to restrict SSH and permit only necessary ports.
- SELinux/AppArmor: enforce restrictive policies if your distribution supports them; test thoroughly before enforcing.
Monitoring, Logging, and Troubleshooting
Maintain visibility into performance and errors:
- Collect Apache access and error logs (usually /var/log/apache2 or /var/log/httpd). Use logrotate to manage sizes.
- Monitor PHP-FPM slow log: configure request_slowlog_timeout and slowlog path to capture slow requests.
- Use system monitoring (top, htop, vmstat) and APM solutions for deep insight (New Relic, Datadog, or open-source tools like Prometheus + Grafana).
- When troubleshooting, check process counts, average response times, and memory per process. If reaching pm.max_children frequently, consider scaling vertically or horizontally.
Choosing the Right VPS for Apache + PHP
When selecting a VPS, consider these factors:
- CPU: PHP is CPU-bound for heavy computation; single-thread performance matters for PHP scripts that are not parallelized.
- Memory: PHP-FPM processes consume RAM; provision enough for peak concurrency plus headroom for Apache and OS.
- Storage I/O: use SSD-backed storage; database-backed applications (MySQL/MariaDB, PostgreSQL) benefit from high IOPS and low latency.
- Networking: bandwidth and latency influence user experience — choose a datacenter close to your audience.
- Scalability: for growth, plan for horizontal scaling (load balancers and multiple VPS instances) or a higher-tier VPS with more CPU/RAM.
For many small-to-medium sites, a VPS with 2–4 vCPUs and 4–8 GB RAM is a practical starting point; adjust based on traffic and application profile.
Deployment Considerations and Best Practices
- Use VirtualHosts for multi-site setups — isolate logs and configurations per site.
- Automate deployments with CI/CD pipelines or tools like Ansible, Capistrano, or GitHub Actions to reduce human error.
- Backup strategy: snapshot the full server regularly and perform database dumps daily with off-site storage.
- Keep packages updated: apply security updates for the OS, Apache, PHP, and extensions; consider automated security patching with maintenance windows.
- Testing: validate configuration changes in a staging environment before production rollouts. Use load testing (wrk, ab) to establish performance baselines.
Advantages and Trade-offs Compared to Other Stacks
The Apache + PHP stack is mature and widely compatible, especially when your applications use .htaccess or depend on Apache modules. Compared to Nginx + PHP-FPM:
- Apache provides per-directory configuration via .htaccess which simplifies per-site tweaks without server reloads; that can be convenient but slightly slower.
- Nginx typically outperforms Apache for serving static assets and uses less memory per connection. For maximum throughput, Nginx + PHP-FPM is often preferred.
- With PHP-FPM, differences between Apache and Nginx narrow for dynamic content, but operational preferences and existing tooling often decide the stack.
Wrap-Up and Next Steps
Installing and optimizing PHP with Apache on a Linux VPS requires aligning the process manager (PHP-FPM vs mod_php), Apache MPM, and system resources to your workload. Focus on correct pool sizing, enabling Opcache, enforcing security best practices, and monitoring runtime behavior. For staging and production, automate deployments, maintain backups, and test changes under load.
If you are evaluating hosting options for deploying this stack, consider a reliable VPS provider that offers SSD storage, predictable CPU/RAM profiles, and datacenter locations near your users. For U.S.-based deployments, VPS.DO’s USA VPS plans are an option worth reviewing: USA VPS at VPS.DO. They provide scalable configurations suitable for web servers running Apache and PHP.