温馨提示×

nginx在centos上的缓存如何配置

小樊
133
2025-02-13 08:06:49
栏目: 智能运维

在CentOS上配置Nginx的缓存,主要涉及两个部分:HTTP缓存和FastCGI缓存。以下是详细的配置步骤:

1. 安装Nginx

首先,确保你已经安装了Nginx。如果没有安装,可以使用以下命令进行安装:

sudo yum install epel-release
sudo yum install nginx

2. 配置HTTP缓存

HTTP缓存可以通过proxy_cache_path指令来配置。编辑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_server;
            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:定义缓存路径和参数。

    • /var/cache/nginx:缓存文件的存储路径。
    • levels=1:2:缓存目录的层级结构。
    • keys_zone=my_cache:10m:定义缓存区域的名称和大小。
    • max_size=1g:缓存的最大总大小。
    • inactive=60m:缓存文件在未被访问后保持的时间。
    • use_temp_path=off:是否使用临时路径。
  • proxy_cache:指定使用的缓存区域。

  • proxy_cache_valid:定义不同响应码的缓存时间。

  • add_header X-Proxy-Cache $upstream_cache_status:添加一个自定义头部,显示缓存状态。

3. 配置FastCGI缓存

FastCGI缓存可以通过fastcgi_cache_path指令来配置。在同一个Nginx配置文件中添加以下内容:

http {
    # FastCGI缓存路径和参数
    fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=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-fpm/php-fpm.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;

            fastcgi_cache fcgi_cache;
            fastcgi_cache_valid 200 302 10m;
            fastcgi_cache_valid 404 1m;
            add_header X-FastCGI-Cache $upstream_cache_status;
        }
    }
}

解释:

  • fastcgi_cache_path:定义FastCGI缓存路径和参数,与HTTP缓存类似。
  • fastcgi_cache:指定使用的缓存区域。
  • fastcgi_cache_valid:定义不同响应码的缓存时间。
  • add_header X-FastCGI-Cache $upstream_cache_status:添加一个自定义头部,显示缓存状态。

4. 重启Nginx

配置完成后,重启Nginx以使更改生效:

sudo systemctl restart nginx

5. 验证缓存

你可以通过访问你的网站并检查响应头中的X-Proxy-CacheX-FastCGI-Cache来验证缓存是否生效。

通过以上步骤,你可以在CentOS上成功配置Nginx的HTTP和FastCGI缓存。

0