linux

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
看了该问题的人还看了