Optimize PHP Performance in Ubuntu with Apache
To enhance the performance of PHP applications running on Apache in Ubuntu, you need a combination of module tuning, configuration adjustments, and caching strategies. Below are actionable steps categorized for clarity:
Ensure critical modules for PHP and performance optimization are enabled. Run the following commands:
sudo a2enmod rewrite deflate expires # Enable URL rewriting, compression, and expiration headers sudo systemctl restart apache2 # Apply changes These modules reduce server load by compressing content, caching responses, and optimizing request routing.
OPcache is a must for PHP performance—it caches precompiled script bytecode to eliminate redundant parsing.
sudo apt install php-opcache # For PHP 7.x/8.x (adjust version as needed) /etc/php/7.x/apache2/php.ini (replace 7.x with your PHP version) and set:[opcache] zend_extension=opcache.so opcache.enable=1 opcache.memory_consumption=128 # Memory allocated for opcode cache (MB) opcache.interned_strings_buffer=8 # Memory for interned strings (MB) opcache.max_accelerated_files=4000 # Max files to cache opcache.revalidate_freq=60 # Check file updates every 60 seconds opcache.fast_shutdown=1 # Faster shutdown process sudo systemctl restart apache2 OPcache can reduce PHP execution time by up to 50% for dynamic pages.
The MPM determines how Apache handles requests. For PHP, event or prefork (for non-thread-safe PHP) are recommended.
apache2ctl -V | grep -i mpm /etc/apache2/mods-enabled/mpm_event.conf and adjust:<IfModule mpm_event_module> StartServers 2 # Initial child processes MinSpareThreads 25 # Minimum idle threads MaxSpareThreads 75 # Maximum idle threads ThreadLimit 64 # Max threads per child ThreadsPerChild 25 # Threads per child process MaxRequestWorkers 150 # Max concurrent requests MaxConnectionsPerChild 0 # Unlimited requests per child (0) </IfModule> /etc/apache2/mods-enabled/mpm_prefork.conf:<IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 1000 # Restart child after 1000 requests </IfModule> sudo systemctl restart apache2 Proper MPM tuning prevents resource exhaustion and improves concurrency.
Adjust PHP settings in /etc/php/7.x/apache2/php.ini to balance performance and resource usage:
memory_limit = 128M # Increase if your app needs more memory (e.g., 256M for heavy apps) max_execution_time = 30 # Time (seconds) before script timeout (increase for long-running tasks) upload_max_filesize = 50M # Max file upload size (adjust per app needs) post_max_size = 50M # Max POST data size display_errors = Off # Disable in production to avoid exposing sensitive info log_errors = On # Log errors to a file error_log = /var/log/php_errors.log # Log file location Restart Apache after changes:
sudo systemctl restart apache2 These settings prevent memory leaks and ensure stable operation under load.
Compress text-based responses (HTML, CSS, JS) to reduce bandwidth usage. Add to your Apache virtual host or global config (/etc/apache2/apache2.conf):
<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json </IfModule> Restart Apache to apply:
sudo systemctl restart apache2 Gzip can reduce response sizes by 50–70%, improving page load times.
PHP-FPM (FastCGI Process Manager) is more efficient than mod_php for handling concurrent PHP requests.
sudo apt install php7.x-fpm # Replace with your PHP version /etc/apache2/sites-available/000-default.conf) and add:<FilesMatch \.php$> SetHandler "proxy:unix:/run/php/php7.x-fpm.sock|fcgi://localhost" </FilesMatch> /etc/php/7.x/fpm/pool.d/www.conf:pm = dynamic # Dynamic process management pm.max_children = 50 # Max PHP processes (adjust based on server RAM) pm.start_servers = 5 # Initial processes pm.min_spare_servers = 5 # Minimum idle processes pm.max_spare_servers = 35 # Maximum idle processes pm.max_requests = 500 # Restart process after 500 requests (prevents memory leaks) sudo systemctl restart apache2 php7.x-fpm PHP-FPM improves scalability and reduces overhead for high-traffic sites.
Reduce database load and speed up dynamic content with caching.
sudo apt install redis-server php-redis Configure your PHP app (e.g., WordPress, Laravel) to use Redis for caching.Regularly monitor your server to identify bottlenecks:
htop or top to track CPU, memory, and disk usage.apachetop (install via sudo apt install apachetop) to monitor request rates and response times./var/log/php_errors.log for warnings or errors.ab (Apache Benchmark) to test performance:ab -n 1000 -c 100 http://yourdomain.com/ This simulates 100 concurrent users making 1000 requests to your site.By implementing these optimizations, you can significantly improve the performance of PHP applications on Apache in Ubuntu. Remember to test changes in a staging environment before applying them to production.