在Linux上配置和优化PHP可以通过多个方面来实现,包括调整PHP-FPM(FastCGI Process Manager)设置、修改PHP配置文件(php.ini)、优化Web服务器配置等。以下是一些常见的优化步骤:
PHP-FPM是一个常用的PHP FastCGI实现,可以通过调整其配置来提高性能。
通常位于 /etc/php/7.x/fpm/pool.d/www.conf 或 /etc/php/7.x/fpm/php-fpm.conf。
; 增加进程管理器进程数
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
; 调整请求处理超时时间
request_terminate_timeout = 30s
; 启用慢日志
slowlog = /var/log/php-fpm/www-slow.log
sudo systemctl restart php7.x-fpm
PHP的配置文件通常位于 /etc/php/7.x/cli/php.ini 或 /etc/php/7.x/apache2/php.ini。
memory_limit = 256M
[opcache]
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
; 禁用不需要的模块
disable_functions = ...
upload_max_filesize = 10M
post_max_size = 10M
如果你使用的是Nginx或Apache作为Web服务器,也需要进行相应的优化。
编辑Nginx配置文件 /etc/nginx/nginx.conf 或站点配置文件。
worker_processes auto;
events {
worker_connections 1024;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
gzip on;
gzip_disable "msie6";
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.x-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
}
编辑Apache配置文件 /etc/apache2/apache2.conf 或站点配置文件。
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 week"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
通过以上步骤,你可以显著提高PHP应用在Linux上的性能。记得在每次修改配置后重启相应的服务以使更改生效。