Fast, Secure Setup: How to Install PHP and Apache on Linux Servers
Get your Linux VPS production-ready in minutes with a fast, secure plan to install PHP and Apache—complete with concrete commands, performance tweaks, and security best practices. Whether you’re hosting a CMS or a custom app, this guide walks Debian/Ubuntu and RHEL-based users through a reliable, production-ready setup so you can deploy with confidence.
Setting up a web stack quickly and securely on a Linux VPS is a common task for site owners, developers, and businesses. This guide walks you through a reliable, production-ready approach to installing PHP and Apache on a Linux server. It focuses on concrete commands, configuration considerations, performance tuning, and security best practices so you can deploy applications with confidence.
Why Apache + PHP still matters
Apache HTTP Server combined with PHP remains a widely used stack for content management systems, custom PHP applications, and legacy systems. Apache’s mature feature set — including mod_rewrite, .htaccess support, and flexible virtual hosts — makes it a great choice for shared-hosting style deployments and applications that rely on per-directory configuration. PHP continues to evolve with performance improvements (OPcache, JIT in newer versions) and a rich ecosystem of frameworks and libraries.
Before diving in, ensure you have a VPS or server with a modern Linux distribution such as Ubuntu LTS, Debian, CentOS, Rocky Linux, or AlmaLinux. This guide uses concrete examples for both Debian/Ubuntu (apt) and RHEL-based systems (yum/dnf).
Preparatory steps
Start with these preparation tasks to minimize surprises.
- Update the system packages:
Debian/Ubuntu:
sudo apt update && sudo apt upgrade -y
RHEL/CentOS/AlmaLinux/Rocky:
sudo dnf update -y or sudo yum update -y
- Create a non-root user with sudo privileges (if not already present).
- Configure basic firewall rules (ufw/firewalld) to allow SSH and HTTP/HTTPS.
Example UFW commands on Ubuntu:
sudo ufw allow OpenSSH
sudo ufw allow 'Apache Full'
sudo ufw enable
Installing Apache
Apache installation is straightforward and includes enabling the server to start on boot and testing a basic site.
Debian/Ubuntu:
sudo apt install apache2 -y
sudo systemctl enable --now apache2
RHEL/CentOS (httpd):
sudo dnf install httpd -y
sudo systemctl enable --now httpd
Verify the server is running and serving the default page by visiting your server IP in a browser or using curl:
curl -I http://your_server_ip
Basic Apache configuration
Key files and directories:
- Ubuntu/Debian: /etc/apache2/ (sites-available, sites-enabled, mods-available, mods-enabled)
- RHEL/CentOS: /etc/httpd/ (conf, conf.d, modules)
Create a virtual host for your domain to separate sites and make management easier. Example for Debian/Ubuntu:
sudo nano /etc/apache2/sites-available/example.com.conf
Place a minimal virtual host:
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>
Enable it:
sudo mkdir -p /var/www/example.com/public_html
sudo chown -R $USER:$USER /var/www/example.com
sudo a2ensite example.com.conf
sudo systemctl reload apache2
Installing PHP
You can run PHP with Apache using mod_php or with PHP-FPM and mod_proxy_fcgi. For production, PHP-FPM is recommended because it isolates PHP processes from the Apache worker processes, improves security and resource control, and integrates well with modern process managers.
Debian/Ubuntu (example installs PHP 8.2):
sudo apt install php8.2 php8.2-fpm php8.2-mysql php8.2-xml php8.2-mbstring php8.2-curl php8.2-zip -y
RHEL/CentOS/AlmaLinux (enable EPEL/Remi or use distribution repos):
Use Remi repo for newer PHP versions, then install php-fpm and extensions.
Enable and start PHP-FPM:
sudo systemctl enable --now php8.2-fpm
Configure Apache to use PHP-FPM
Enable required modules and configure a proxy between Apache and PHP-FPM.
Debian/Ubuntu:
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.2-fpm
sudo systemctl reload apache2
Update the virtual host to pass PHP files to FPM (example snippet):
<FilesMatch .php$>
SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost/"
</FilesMatch>
PHP configuration and performance tuning
Key settings are located in php.ini and in pool configuration files for PHP-FPM (e.g., /etc/php/8.2/fpm/pool.d/www.conf). Consider these changes based on your application and VPS size:
- memory_limit — set according to application needs (e.g., 128M–512M)
- upload_max_filesize and post_max_size — for uploads
- max_execution_time — increase for long-running scripts
- opcache.enable=1 and opcache.memory_consumption — enable OPcache for significant performance gains
- pm = dynamic (or ondemand) in PHP-FPM pools, and tune pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers based on available RAM and average PHP process size
Estimate pm.max_children as: available_memory_for_php / average_memory_per_php_process. Monitor with tools like top, htop, or ps to find the average process size.
Security hardening
Security should be layered: OS, service, web app, and network.
Basic server hardening
- Use a non-root user for daily tasks and disallow root SSH login: edit /etc/ssh/sshd_config to set
PermitRootLogin no. - Use public key authentication for SSH, disable password authentication if possible:
PasswordAuthentication no. - Enable and configure firewall (ufw or firewalld) to limit exposed ports.
- Keep packages updated and enable unattended security updates if acceptable for your environment.
Apache and PHP-specific security
- Disable unnecessary Apache modules. Use
apachectl -Mto list modules and remove unused ones. - Set proper file and directory permissions. The document root should be owned by a deploy user and use restrictive permissions (folders 755, files 644). Avoid giving web server user write permissions except where explicitly needed (uploads, cache).
- Harden PHP by disabling dangerous functions in php.ini:
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source(evaluate based on app requirements). - Use mod_security and mod_evasive or a WAF for extra request-level protection.
TLS/HTTPS
Always run sites over HTTPS. Use Let’s Encrypt for free TLS certificates and automate renewal with Certbot.
Example Certbot command for Apache:
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d example.com -d www.example.com
Follow the prompts and enable automatic renewal (certbot installs a cron job or systemd timer). Verify HTTPS headers and TLS configuration with services like Qualys SSL Labs.
Monitoring, logging and backups
Operational readiness includes monitoring resource usage and ensuring logs and backups are available for troubleshooting and disaster recovery.
- Enable and monitor Apache access and error logs: /var/log/apache2/ or /var/log/httpd/
- Use tools like fail2ban to react to suspicious login attempts and web abuse.
- Set up system monitoring: Prometheus + node_exporter, Netdata, or managed monitoring offered by your VPS provider.
- Schedule regular backups of web files and databases (use mysqldump or LVM snapshots). Store backups offsite or in object storage.
Use cases and deployment workflows
The Apache + PHP stack covers several common scenarios:
- WordPress, Joomla, Drupal and other PHP CMS hosting — Apache’s .htaccess support and mod_rewrite make migration straightforward.
- Custom PHP applications and legacy codebases — PHP-FPM allows parallel deployments with different PHP versions via multiple pools or sockets.
- Staging and testing environments — use Apache virtual hosts with separate document roots or containers to simulate production.
For continuous deployment, consider using Git hooks, CI/CD pipelines (GitHub Actions, GitLab CI), or deployment tools (rsync, Deployer, Capistrano) to push code to the server securely. Use environment-specific configuration outside the repository (environment variables or separate config files) to avoid leaking secrets.
Comparisons and trade-offs
When choosing technologies and configurations, weigh these trade-offs:
- mod_php vs PHP-FPM: mod_php is simpler but ties PHP to Apache processes and can increase memory usage. PHP-FPM offers better isolation and resource control.
- Apache vs Nginx: Apache provides .htaccess and mature module ecosystem. Nginx has lower memory footprint and excels at serving static content and reverse proxying. Many modern architectures use Nginx as a reverse proxy and Apache or PHP-FPM behind it.
- Single VPS vs managed hosting: VPS gives control and cost-efficiency; managed platforms save time but may restrict deep configuration.
Recommendations for choosing a VPS
For production PHP and Apache deployments, select a VPS plan with:
- Enough RAM to handle PHP-FPM processes (at least 1–2 GB for small sites; 4+ GB for medium workloads).
- SSD storage for faster I/O and database performance.
- Predictable CPU share or dedicated vCPU if you have CPU-intensive tasks.
- Reliable snapshot or backup options for quick recovery.
Evaluate provider network performance, datacenter locations, and support options. If you host primarily U.S. visitors, choosing a provider with data centers in the U.S. can lower latency.
Quick troubleshooting checklist
- 500 Internal Server Error — check Apache error logs and PHP-FPM logs, validate file permissions, and confirm PHP handler configuration.
- Blank page — enable display_errors temporarily or check logs; often a fatal PHP error or missing extension.
- Slow responses — monitor CPU, I/O, and memory; enable OPcache and tune PHP-FPM pool sizes.
- Certbot/HTTPS issues — verify DNS, open ports 80/443, and run Certbot in verbose mode to see errors.
With a secure baseline and proper tuning, Apache + PHP can serve a wide range of workloads reliably. The steps above provide a pragmatic path from a fresh Linux server to a production-ready web host.
Conclusion
Installing PHP and Apache on a Linux VPS is a routine but critical task for web administrators. By choosing PHP-FPM, configuring Apache virtual hosts, hardening server and application settings, enabling HTTPS, and tuning performance, you can achieve a fast and secure web stack suitable for CMS platforms and custom applications. Monitor resource consumption, automate backups, and adopt a consistent deployment workflow to reduce downtime and improve maintainability.
If you’re looking for a reliable environment to deploy this stack, consider a VPS with solid performance and U.S.-based datacenters. Learn more about hosting options at VPS.DO and explore their USA VPS plans at https://vps.do/usa/. A well-provisioned VPS makes it easier to follow the security and tuning recommendations above and deliver a responsive, secure PHP + Apache service to your users.