在Nginx中配置缓存主要涉及到两个模块:proxy_cache和fastcgi_cache。以下是一个基本的配置示例,展示了如何在Nginx中设置HTTP缓存。
首先,确保你的Nginx版本支持缓存功能。你可以通过运行nginx -V命令来检查。如果你看到--with-http_cache_module和--with-http_fastcgi_cache_module(或类似的选项),那么你的Nginx版本支持缓存。
打开你的Nginx配置文件。通常位于/etc/nginx/nginx.conf或/etc/nginx/sites-available/your_domain.conf。
在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 {
# ...
location / {
# ...
proxy_pass http://backend_server;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Proxy-Cache $upstream_cache_status;
}
location ~ \.php$ {
# ...
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_cache my_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;
}
}
}
在这个例子中,我们首先在http块中定义了一个名为my_cache的缓存区域。我们为缓存设置了存储路径、缓存级别、键值、最大大小、非活动时间和是否使用临时路径等参数。
然后,在server块中,我们为location /和location ~ \.php$分别启用了缓存。我们通过proxy_cache指令将缓存区域应用到这两个位置,并使用proxy_cache_valid指令设置了不同响应代码的缓存时间。最后,我们使用add_header指令添加了一个名为X-Proxy-Cache的自定义响应头,用于显示缓存状态。
sudo nginx -t # 检查配置文件语法是否正确
sudo nginx -s reload # 重新加载配置文件
现在,Nginx应该已经根据你的配置为指定的请求启用缓存了。你可以通过查看响应头中的X-Proxy-Cache字段来验证缓存是否生效。