Skip to content

Instantly share code, notes, and snippets.

@bageljp
Created May 4, 2018 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bageljp/2b4b6bbc54f3d8d605fb5c63c870035e to your computer and use it in GitHub Desktop.
Save bageljp/2b4b6bbc54f3d8d605fb5c63c870035e to your computer and use it in GitHub Desktop.
nginx_maintenance_user_id
  • POSTのbodyの中にuser_idというパラメータが含まれており、そのuser_idが特定の値(この例だと1000,2000,5000)の場合のみリクエストを許可
  • それ以外はメンテナンスを返す
log_format postdata 'request_body: $request_body';
# mapで評価することでPOSTの中身を利用してレスポンスヘッダやログの中身を変更することができる
map $request_body $user_id {
default 1000;
# ok: x-www-form-urlencoded
~user_id=([^&]+) $1;
# ok: raw(json)
~"user_id"\ *:\ *([^,"]+) $1;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
access_log logs/host.access.log postdata;
location / {
root /var/www/html;
index index.html index.htm;
}
location /api/ {
# ifで判定した場合、$request_bodyにPOSTのデータが入っていない
# mapで評価した場合でも判定が結局ifで行うので変わらず
# 参考:https://recruit.gmo.jp/engineer/jisedai/blog/nginx-post-log-filter/
# ----------------------------------------------------------------------
#set $user_id "false";
#if ($request_body ~* "(?:^|&;)user_id=([^&;]+)") {
# set $user_id $1;
#}
#if ($user_id != 1000) {
# return 503;
#}
root /var/www/html;
index index.html index.htm;
#add_header user_id $user_id;
proxy_pass http://127.0.0.1/post_gif;
# luaで定義したuser_id以外はメンテナンスを返す
access_by_lua_block {
t={}
t[#t+1]=1000
t[#t+1]=2000
t[#t+1]=5000
-- 全リクエストで処理するのを防ぐため POST かどうかチェックする
method_name = ngx.req.get_method()
if method_name == "POST" then
-- request_body を明示的に読み込む
ngx.req.read_body()
-- POST の値があるかチェック
local args, err = ngx.req.get_post_args()
-- 何もないとき
if not args then
ngx.log(ngx.ERR, "failed to no parameters: ", err)
end
local cjson = require("cjson")
local body_data = ngx.req.get_body_data()
local decode_data = cjson.decode(body_data)
local user_id = decode_data["user_id"]
local maintenance = 1
-- ngx.say(user_id)
for i = 1, #t do
local s = t[i]
if t[i] == user_id then
maintenance = 0
break
end
end
if maintenance == 1 then
return ngx.exit(503)
end
end
}
}
location = /post_gif {
access_log off;
empty_gif;
}
#error_page 404 /404.html;
error_page 405 =200 $uri;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/openresty/nginx/html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment