在LNMP(Linux, Nginx, MySQL, PHP)环境中配置缓存系统可以显著提高网站性能。以下是配置Nginx缓存和PHP-FPM缓存的步骤:
确保你已经安装了Nginx,并且启用了必要的模块,如ngx_cache
和ngx_cache_purge
。
sudo apt-get update
sudo apt-get install nginx
编辑Nginx配置文件(通常是/etc/nginx/nginx.conf
或/etc/nginx/conf.d/default.conf
),添加缓存路径和相关配置。
http {
# 缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Proxy-Cache $upstream_cache_status;
}
# 清除缓存
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge my_cache $scheme://$host$request_uri;
}
}
upstream backend {
server unix:/tmp/php-fpm.sock;
}
}
OPcache是PHP的一个内置扩展,可以显著提高PHP脚本的执行速度。
sudo apt-get install php-opcache
编辑PHP-FPM配置文件(通常是/etc/php/7.x/fpm/php.ini
),启用并配置OPcache。
[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
opcache.fast_shutdown=1
sudo systemctl restart nginx
sudo systemctl restart php7.x-fpm
访问你的网站,查看响应头中的X-Proxy-Cache
字段,确认请求是否被缓存。
通过PHP脚本输出opcache_get_status()
的结果,确认OPcache是否正常工作。
<?php
print_r(opcache_get_status());
?>
通过以上步骤,你可以在LNMP环境中成功配置Nginx和PHP-FPM的缓存系统,从而提高网站的性能和响应速度。