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:
1. Enable Essential Apache Modules
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.
2. Install and Configure OPcache
OPcache is a must for PHP performance—it caches precompiled script bytecode to eliminate redundant parsing.
- Install OPcache:
sudo apt install php-opcache # For PHP 7.x/8.x (adjust version as needed) - Enable OPcache: Edit
/etc/php/7.x/apache2/php.ini(replace7.xwith 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 - Restart Apache:
sudo systemctl restart apache2
OPcache can reduce PHP execution time by up to 50% for dynamic pages.
3. Adjust Apache MPM (Multi-Processing Module)
The MPM determines how Apache handles requests. For PHP, event or prefork (for non-thread-safe PHP) are recommended.
- Check Current MPM:
apache2ctl -V | grep -i mpm - Configure Event MPM (default for modern Apache): Edit
/etc/apache2/mods-enabled/mpm_event.confand adjust: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) - For Prefork MPM (if using non-thread-safe PHP): Edit
/etc/apache2/mods-enabled/mpm_prefork.conf:StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 1000 # Restart child after 1000 requests - Restart Apache:
sudo systemctl restart apache2
Proper MPM tuning prevents resource exhaustion and improves concurrency.
4. Optimize PHP Configuration
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.
5. Enable Gzip Compression
Compress text-based responses (HTML, CSS, JS) to reduce bandwidth usage. Add to your Apache virtual host or global config (/etc/apache2/apache2.conf):
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
Restart Apache to apply:
sudo systemctl restart apache2
Gzip can reduce response sizes by 50–70%, improving page load times.
6. Use PHP-FPM for Better Process Management
PHP-FPM (FastCGI Process Manager) is more efficient than mod_php for handling concurrent PHP requests.
- Install PHP-FPM:
sudo apt install php7.x-fpm # Replace with your PHP version - Configure Apache to Use PHP-FPM: Edit your virtual host file (e.g.,
/etc/apache2/sites-available/000-default.conf) and add:SetHandler "proxy:unix:/run/php/php7.x-fpm.sock|fcgi://localhost" - Adjust PHP-FPM Settings: Edit
/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) - Restart Services:
sudo systemctl restart apache2 php7.x-fpm
PHP-FPM improves scalability and reduces overhead for high-traffic sites.
7. Implement Caching Mechanisms
Reduce database load and speed up dynamic content with caching.
- Use Redis for Object Caching: Install Redis and the PHP Redis extension:
Configure your PHP app (e.g., WordPress, Laravel) to use Redis for caching.sudo apt install redis-server php-redis - Cache Database Queries: In your app, implement query caching (e.g., WordPress’s WP_Object_Cache) to store frequent query results.
- Use a CDN: Offload static assets (images, CSS, JS) to a CDN like Cloudflare to reduce server load and improve delivery speed.
8. Monitor and Analyze Performance
Regularly monitor your server to identify bottlenecks:
- System Resources: Use
htoportopto track CPU, memory, and disk usage. - Apache Metrics: Use
apachetop(install viasudo apt install apachetop) to monitor request rates and response times. - PHP Errors: Check
/var/log/php_errors.logfor warnings or errors. - Benchmarking: Use tools like
ab(Apache Benchmark) to test performance:
This simulates 100 concurrent users making 1000 requests to your site.ab -n 1000 -c 100 http://yourdomain.com/
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.
以上就是关于“Ubuntu Apache配置如何优化PHP性能”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm