在LAMP(Linux+Apache+MySQL+PHP)环境中优化PHP性能需要从多个层面进行配置和调整。以下是一套全面的优化方案:
; 禁用不必要的函数
disable_functions = exec,passthru,shell_exec,system,proc_open,popen
; 错误报告设置(生产环境)
error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED
display_errors = Off
log_errors = On
; 内存限制(根据应用需求调整)
memory_limit = 128M
; 脚本执行时间
max_execution_time = 30
; 上传文件大小
upload_max_filesize = 10M
post_max_size = 12M
; OPcache配置(强烈推荐启用)
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1
; 其他优化
realpath_cache_size = 256k
realpath_cache_ttl = 3600
# 使用MPM prefork或worker(根据需求选择)
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>
# 启用压缩
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
# KeepAlive设置(根据服务器负载调整)
KeepAlive On
KeepAliveTimeout 2
MaxKeepAliveRequests 100
# 禁用不必要的模块
# 通常可以禁用: mod_imap, mod_include, mod_info, mod_userdir, mod_autoindex
[mysqld]
# 缓冲区和缓存设置
key_buffer_size = 256M
query_cache_size = 64M
query_cache_limit = 2M
table_open_cache = 1024
sort_buffer_size = 4M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
join_buffer_size = 8M
# InnoDB设置(如果使用InnoDB)
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1
# 其他优化
tmp_table_size = 64M
max_heap_table_size = 64M
max_connections = 100
thread_cache_size = 8
使用PHP加速器:
监控工具:
替代方案考虑:
通过以上多层次的优化,可以显著提升LAMP环境下PHP应用的性能。建议每次修改后都进行基准测试,确保优化措施确实有效。