Request Body 에 특정 문자가 있으면 요청 버리기
- Published on
왜?
보통은 path 패턴등으로 드롭하면 되나, 어떤 사이트가 특별한 경우로 request body 를 검사하여 요청을 중단해야 하는 경우가 있었다. 서버가 JSON-RPC 로 작동되는데 따라서 모든 호출의 endpoint 가 동일하고 body 의 JSON 내용에 의해 backend 서버에 전달할지 말지를 결정하는 경우였다.
방법
Nginx 에 lua 모듈로 아래와 같이 설정하여 필터링할 수 있다.
https://github.com/openresty/lua-nginx-module#body_filter_by_lua
location / {
body_filter_by_lua_block {
local data = ngx.arg[1]
if string.find(data, "1111") then
ngx.exit(404)
end
}
# Your normal configuration goes here
}
nginx 를 lua 모듈을 포함하여 빌드한다. (lua 는 ndk 모듈에 의존함으로 같이 포함한다)
git clone git@github.com:nginxinc/docker-nginx.git
cd modules
docker build --build-arg ENABLED_MODULES="ndk lua" -t nginx-with-lua .
nginx 설정 (/etc/nginx/nginx.conf) 최상단에 lua 모듈을 로딩한다.
load_module modules/ndk_http_module.so;
load_module modules/ngx_http_lua_module.so;
load_module modules/ngx_stream_lua_module.so;
http request body 에 특정 문자열("1111") 이 있을 경우 drop 하는 lua block 설정 예시이다.
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.vrerv.com;
ssl_certificate /etc/nginx/ssl/vrerv.com.crt;
ssl_certificate_key /etc/nginx/ssl/vrerv.com.key;
location / {
proxy_pass http://localnode:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
body_filter_by_lua_block {
local data = ngx.arg[1]
if string.find(data, "1111") then
ngx.exit(404)
end
}
}
}