Nginx实现字符串密钥认证

当前文章收录状态:
未收录

废话不多说,直接上配置文件:

server {
listen 9999;
server_name localhost;
location /docs {
proxy_pass http://127.0.0.1:8999/docs;
}
location /openapi.json {
proxy_pass http://127.0.0.1:8999/openapi.json;
}
location / {
# 设置密钥
set $key "123456";
set $iskey false;
# 如果路由参数中的key等于密钥
if ($arg_key = $key) {
set $iskey true;
}
# 如果请求头参数中的key等于密钥
if ($http_key = $key) {
set $iskey true;
}
# 上方2个条件均未满足
if ($iskey = false) {
rewrite ^ /error403 last;
}
proxy_pass http://127.0.0.1:8999;
}
location = /error403 {
internal;
add_header Content-Type 'application/json';
return 200 '{"error": "密钥错误"}';
}
}
server {
    listen       9999;
    server_name  localhost;
    
    location /docs {
        proxy_pass http://127.0.0.1:8999/docs;
    }
    
    location /openapi.json {
        proxy_pass http://127.0.0.1:8999/openapi.json;
    }

    location / {
        # 设置密钥
        set $key "123456";
        set $iskey false;
        
        # 如果路由参数中的key等于密钥
        if ($arg_key = $key) {
            set $iskey true;
        }

        # 如果请求头参数中的key等于密钥
        if ($http_key = $key) {
            set $iskey true;
        }
        
        # 上方2个条件均未满足
        if ($iskey = false) {
            rewrite ^ /error403 last;
        }
    
        proxy_pass http://127.0.0.1:8999;
    }

    location = /error403 {
        internal;
        add_header Content-Type 'application/json';
        return 200 '{"error": "密钥错误"}';
    }
}
server { listen 9999; server_name localhost; location /docs { proxy_pass http://127.0.0.1:8999/docs; } location /openapi.json { proxy_pass http://127.0.0.1:8999/openapi.json; } location / { # 设置密钥 set $key "123456"; set $iskey false; # 如果路由参数中的key等于密钥 if ($arg_key = $key) { set $iskey true; } # 如果请求头参数中的key等于密钥 if ($http_key = $key) { set $iskey true; } # 上方2个条件均未满足 if ($iskey = false) { rewrite ^ /error403 last; } proxy_pass http://127.0.0.1:8999; } location = /error403 { internal; add_header Content-Type 'application/json'; return 200 '{"error": "密钥错误"}'; } }

© 版权声明
THE END
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=270198dipw4ko
点赞15赞赏 分享
pencil and a dream can take you anywhere.
拿起笔,写下你的梦想,你的人生就从此刻起航
评论 抢沙发

请登录后发表评论

    暂无评论内容