在LNMP(Linux, Nginx, MySQL, PHP)环境中配置缓存可以显著提高网站的性能。以下是一些常见的缓存配置方法:
Nginx 提供了多种缓存机制,包括代理缓存和FastCGI缓存。
安装 Nginx 缓存模块:
sudo apt-get install nginx-extras
配置 Nginx 缓存:
编辑 Nginx 配置文件(通常是 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/default),添加以下内容:
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;
        }
    }
}
解释:
proxy_cache_path:定义缓存路径和参数。keys_zone:定义缓存区域的名称和大小。max_size:定义缓存的最大大小。inactive:定义缓存项在不被访问后多久失效。use_temp_path:是否使用临时路径。启用 FastCGI 缓存: 在 Nginx 配置文件中添加以下内容:
http {
    fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=my_fcgi_cache:10m max_size=1g inactive=60m use_temp_path=off;
    server {
        listen 80;
        server_name example.com;
        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
            fastcgi_cache my_fcgi_cache;
            fastcgi_cache_valid 200 302 10m;
            fastcgi_cache_valid 404 1m;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
        }
    }
}
PHP 提供了多种缓存机制,包括 OPcache 和文件缓存。
安装 OPcache: 大多数现代 PHP 版本已经内置了 OPcache,无需额外安装。
配置 OPcache:
编辑 php.ini 文件(通常是 /etc/php/7.4/cli/php.ini 或 /etc/php/7.4/fpm/php.ini),添加或修改以下内容:
[opcache]
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
MySQL 提供了查询缓存和 InnoDB 缓冲池。
启用查询缓存:
在 MySQL 配置文件(通常是 /etc/mysql/my.cnf 或 /etc/mysql/mysql.conf.d/mysqld.cnf)中添加以下内容:
[mysqld]
query_cache_type=1
query_cache_size=64M
重启 MySQL 服务:
sudo systemctl restart mysql
配置 InnoDB 缓冲池: 在 MySQL 配置文件中添加或修改以下内容:
[mysqld]
innodb_buffer_pool_size=1G
重启 MySQL 服务:
sudo systemctl restart mysql
通过以上步骤,你可以在 LNMP 环境中配置多种缓存机制,从而提高网站的性能和响应速度。根据你的具体需求和服务器资源,调整缓存参数以达到最佳效果。