在 CentOS 上搭建的 LAMP(Linux + Apache + MySQL/MariaDB + PHP)环境,如果感觉访问慢、响应慢,可以从系统层、Web 层、数据库层、PHP 层、缓存层几个方向来加速。下面给你一套实用、可落地的优化方案。
systemctl list-unit-files --type=service | grep enabled
关闭不必要的服务(如 postfix、cups 等)。
vi /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
vi /etc/sysctl.conf
示例:
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
执行:
sysctl -p
推荐 event(PHP-FPM) 或 worker
查看:
httpd -V | grep MPM
编辑:
vi /etc/httpd/conf.modules.d/00-mpm.conf
启用:
LoadModule mpm_event_module modules/mod_mpm_event.so
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
a2enmod deflate # CentOS 通常是已编译
或手动加载:
LoadModule deflate_module modules/mod_deflate.so
配置:
AddOutputFilterByType DEFLATE text/html text/css application/javascript
Options -Indexes
yum install php-fpm
systemctl enable php-fpm
Apache 使用:
proxy:unix:/run/php-fpm/www.sock|fcgi://localhost
yum install php-opcache
php.ini:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
memory_limit = 256M
max_execution_time = 30
upload_max_filesize = 20M
编辑:
vi /etc/my.cnf.d/server.cnf
示例(2GB 内存):
innodb_buffer_pool_size = 1G
query_cache_size = 64M
query_cache_type = 1
SHOW VARIABLES LIKE 'slow_query%';
开启慢日志,优化 SQL。
避免 SELECT *,给常用查询字段加索引。
yum install redis
systemctl start redis
PHP 使用:
yum install php-redis
<FilesMatch "\.(js|css|png|jpg)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
htop、iotop、mysqltuner 排查瓶颈top
free -h
iostat -x 1
mysqltuner
ab -n 1000 -c 100 http://localhost/
如果你愿意,可以告诉我:
我可以直接给你一份可复制的优化配置文件。