溫馨提示×

LNMP環境中如何配置緩存系統

小樊
35
2025-06-04 16:46:37
欄目: 編程語言

在LNMP(Linux, Nginx, MySQL, PHP)環境中配置緩存系統可以顯著提高網站性能。以下是配置Nginx緩存和PHP-FPM緩存的步驟:

1. 配置Nginx緩存

1.1 安裝Nginx和相關模塊

確保你已經安裝了Nginx,并且啟用了必要的模塊,如ngx_cachengx_cache_purge。

sudo apt-get update
sudo apt-get install nginx

1.2 配置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;
    }
}

2. 配置PHP-FPM緩存

2.1 安裝OPcache

OPcache是PHP的一個內置擴展,可以顯著提高PHP腳本的執行速度。

sudo apt-get install php-opcache

2.2 配置PHP-FPM

編輯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

3. 重啟服務

3.1 重啟Nginx

sudo systemctl restart nginx

3.2 重啟PHP-FPM

sudo systemctl restart php7.x-fpm

4. 驗證緩存配置

4.1 檢查Nginx緩存

訪問你的網站,查看響應頭中的X-Proxy-Cache字段,確認請求是否被緩存。

4.2 檢查PHP-FPM緩存

通過PHP腳本輸出opcache_get_status()的結果,確認OPcache是否正常工作。

<?php
print_r(opcache_get_status());
?>

通過以上步驟,你可以在LNMP環境中成功配置Nginx和PHP-FPM的緩存系統,從而提高網站的性能和響應速度。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女