在Ubuntu上優化Apache和PHP的性能,可以通過以下幾個方面來實現:
安裝Apache:
sudo apt update
sudo apt install apache2
啟用必要的模塊:
sudo a2enmod rewrite
sudo systemctl restart apache2
安裝PHP及其常用擴展:
sudo apt install php libapache2-mod-php php-mysql php-curl php-gd php-mbstring php-xml php-zip
重啟Apache以應用更改:
sudo systemctl restart apache2
編輯/etc/php/7.4/apache2/php.ini
(根據你的PHP版本調整路徑):
內存限制:
memory_limit = 128M
執行時間:
max_execution_time = 30
文件上傳大小:
upload_max_filesize = 50M
post_max_size = 50M
錯誤日志:
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
OpenSSL:
openssl.cafile=/etc/ssl/certs/ca-certificates.crt
編輯/etc/apache2/apache2.conf
或/etc/apache2/httpd.conf
:
KeepAlive:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
MaxClients:
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 300
壓縮:
EnableSendfile on
EnableMMAP on
EnableSendfile off
日志級別:
LogLevel warn
OPcache可以顯著提高PHP腳本的執行速度。
安裝OPcache:
sudo apt install php-opcache
啟用OPcache:
編輯/etc/php/7.4/apache2/php.ini
,確保以下行未被注釋:
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
使用如Redis或Memcached作為PHP的緩存系統,可以進一步提高性能。
安裝Redis:
sudo apt install redis-server
安裝PHP Redis擴展:
sudo apt install php-redis
配置PHP使用Redis:
編輯/etc/php/7.4/apache2/php.ini
,添加:
extension=redis.so
使用工具如top
、htop
、Apache Bench
(ab)等來監控服務器的性能,并根據需要進行調整。
通過以上步驟,你可以顯著提高Ubuntu上Apache和PHP的性能。記得在每次更改配置后重啟相應的服務以應用更改。