在Debian系统上配置LNMP(Linux, Nginx, MySQL, PHP)的缓存,通常涉及到Nginx的反向代理缓存和PHP的OPcache。以下是详细的步骤:
如果你还没有安装Nginx,可以使用以下命令进行安装:
sudo apt update
sudo apt install nginx
编辑Nginx配置文件,通常位于/etc/nginx/nginx.conf
或/etc/nginx/sites-available/default
。
确保Nginx编译时启用了缓存模块。你可以通过以下命令检查:
nginx -V 2>&1 | grep --color=auto -o with-http_cache_module
如果输出中包含with-http_cache_module
,则表示已启用。
在Nginx配置文件中添加缓存相关的配置。例如,在http
块中添加:
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 /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public";
}
}
upstream backend {
server unix:/var/run/php/php7.4-fpm.sock;
}
}
OPcache可以显著提高PHP脚本的执行速度。
如果你使用的是PHP 7.2及以上版本,OPcache已经包含在内。如果没有,可以使用以下命令安装:
sudo apt install php-opcache
编辑PHP配置文件,通常位于/etc/php/7.4/cli/php.ini
或/etc/php/7.4/fpm/php.ini
。
添加或修改以下配置:
[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
配置完成后,重启Nginx和PHP-FPM服务以应用更改:
sudo systemctl restart nginx
sudo systemctl restart php7.4-fpm
你可以通过访问你的网站并检查响应头中的X-Proxy-Cache
字段来验证Nginx缓存是否生效。例如:
curl -I http://example.com
如果响应头中包含X-Proxy-Cache: HIT
,则表示缓存生效。
通过以上步骤,你可以在Debian系统上成功配置LNMP的缓存,提高网站的性能和响应速度。