request-cookies-filter: 细粒度请求Cookie控制
安装
您可以在任何基于RHEL的发行版中安装此模块,包括但不限于:
- RedHat Enterprise Linux 7、8、9和10
- CentOS 7、8、9
- AlmaLinux 8、9
- Rocky Linux 8、9
- Amazon Linux 2和Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install nginx-module-request-cookies-filter
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install nginx-module-request-cookies-filter
通过在/etc/nginx/nginx.conf的顶部添加以下内容来启用该模块:
load_module modules/ngx_http_request_cookies_filter_module.so;
本文档描述了nginx-module-request-cookies-filter v0.1.0,发布于2026年1月6日。
概述
http {
server {
listen 80;
server_name example.com;
location / {
# 如果存在名为"a"的Cookie,则将其设置为1。否则,添加一个名为"a"的Cookie,值为1。
set_request_cookie a 1;
# 如果存在名为"b"的Cookie,则不做任何操作。否则,添加一个名为"a"的Cookie,值为1。
add_request_cookie b 2;
# 如果存在名为"c"的Cookie,则将其设置为3。否则,不做任何操作。
modify_request_cookie c 3;
# 如果存在名为"d"的Cookie,则删除它。否则,不做任何操作。
clear_request_cookie d;
# 条件过滤。仅在变量$http_a不为空或'0'时生效。
set_request_cookie e 4 if=$http_a;
# 将过滤后的Cookie发送到上游。
proxy_set_header Cookie $filtered_request_cookies;
proxy_pass http://127.0.0.1:8080;
}
}
}
指令
set_request_cookie
语法: set_request_cookie cookie_name value [if=condition];
默认值: —
上下文: http, server, location
设置Cookie的值。如果Cookie已经存在,将被修改。
Cookie名称区分大小写,以下内容相同。
add_request_cookie
语法: add_request_cookie cookie_name value [if=condition];
默认值: —
上下文: http, server, location
添加一个新Cookie。如果Cookie已经存在,则忽略该操作。
modify_request_cookie
语法: modify_request_cookie cookie_name value [if=condition];
默认值: —
上下文: http, server, location
修改现有Cookie的值。如果Cookie不存在,则忽略该操作。
clear_request_cookie
语法: clear_request_cookie cookie_name [if=condition];
默认值: —
上下文: http, server, location
从请求头中移除一个Cookie。
变量
$filtered_request_cookies
一个以分号分隔的过滤Cookie字符串。包含应用所有过滤规则后的最终Cookie字符串。
如果没有应用过滤规则,则该变量包含原始Cookie字符串,如$http_cookie。
示例:
location / {
set_request_cookie user "test_user";
add_request_cookie theme "dark";
# 如果请求不包含任何Cookie,将会是"user=test_user; theme=dark"。
proxy_set_header Cookie $filtered_request_cookies;
proxy_pass http://backend;
}
GitHub
您可以在nginx-module-request-cookies-filter的GitHub 仓库中找到此模块的其他配置提示和文档。