在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的緩存系統,從而提高網站的性能和響應速度。