Nginx 开启 Fastcgi 缓存以及 rewrite 去掉请求参数Query string

技巧 shanhuhai 7599℃ 0评论

开启 fastcgi 缓存

打开 nginx 的配置

首先要在 server{} 外定义缓存区块

fastcgi_cache_path /data/cache levels=1:2 keys_zone=content:1000m inactive=20m;
fastcgi_cache_key $request_method://$host$request_uri;
fastcgi_cache_use_stale error timeout invalid_header http_500;

fastcgi_cache_path 用于定义一个缓存区块, /data/cache 表示将缓存存储在此目录,
levels=1:2 表示在缓存目录中创建2层目录,第一层目录名用1个字符,第二层目录名用2个字符
keys_zone=content:1000m 表示将缓存区块命名为”content”, 大小为 “1000MB”
inactive=20m 表示如果缓存在 20分钟内没有被访问则删除

fastcgi_cache_key 用于设置缓存的 Key 值,用一组变量拼接而成。
fastcgi_cache_use_stale 用于定义在哪些情况下使用过期的缓存

然后我们可以在动态请求 php 的 location 中, 添加 fastcgi cache的缓存配置

    location ~ .*\.php$ {
# --- 增加的 fastcgi cache
       fastcgi_cache content;
       fastcgi_cache_valid 200 302 5m;
       fastcgi_cache_valid 404 1d;
       fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
# --- fastcgi ended
        fastcgi_pass 127.0.0.1:9001;
        fastcgi_index index.php;
        include fastcgi.conf;
        access_log /var/log/server/tengine/user.jnnews.tv_access.fs.log fs;
    }

其中 fastcgi_cache 表示使用名称为 “content” 的缓存块(我们刚刚在 server 外定义的)

fastcgi_cache_valid 200 302 5m
fastcgi_cache_valid 404 1d;

表示将php-fpm响应为 “200” 和 “302” 的状态码缓存 5分钟, 将 “404” 的状态响应缓存 1天

fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

表示忽略php-fpm 响应中的 “Cache-Control“ “Expires” “Set-Cookie” 头,如果没有这个指令,开启了 Session的 请求是不会被 fastcgi 缓存的

rewrite 请求去掉 Query String 查询参数

参考以下示例配置,以下配置表示,如果首页请求的 Query String 不为空则 Rewrite 到首页,并去掉 Query string:

  location = / { 
        if ($query_string != "") {   
            rewrite ^/$ /? permanent;
        }   
        try_files $uri $uri/ /index.php?$query_string;
    }  

配置的关键点在 rewrite 到的目标地址后加了一个 “?” 就去掉了查询参数,
例如现在访问 “/?xxx” 将被 301 重定向到 “/”

转载请注明:大后端 » Nginx 开启 Fastcgi 缓存以及 rewrite 去掉请求参数Query string

付费咨询
喜欢 (3)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址