Nginx cookie登录认证插件

项目仓库: https://github.com/Akvicor/ngx_auth_cookie_module
已编译源: https://deb.ksyaki.com/nginx/
博客链接: https://www.ksyaki.com/archives/nginx-cookiedeng-lu-ren-zheng-cha-jian

  • 使用 htpasswd 文件校验用户名和密码。
  • 登录成功后签发 HMAC-SHA256 签名 Cookie。
  • 后续请求通过 Cookie 自动认证,无需服务端保存会话。
  • 支持会话过期、登出、自定义登录页面和登录跳转。
  • Cookie 与请求域名、用户文件及密码哈希绑定,修改密码后旧会话失效。
  • 提供 $auth_cookie_user 变量记录当前认证用户。
  • 支持在 server 或 location 级别启用认证。

核心流程是:未认证请求跳转登录页,登录成功后设置 Cookie并返回原页面,后续验签通过即可访问。

2026-09-03-235522_817x621_scrot

安装

如果是使用的Debian系统,可以直接使用已经编译好的源通过apt安装

配置

server {
    listen 443 ssl;
    server_name app.example.com;

    auth_cookie_user_file /etc/nginx/htpasswd;
    auth_cookie_page basic;

    # auth_cookie_name auth_cookie;
    # auth_cookie_secure on;
    # auth_cookie_secret /etc/nginx/auth_cookie.secret;
    # auth_cookie_session_ttl 12h;
    # auth_cookie_title "Restricted Content";
    # auth_cookie_login_uri /_login;
    # auth_cookie_logout_uri /_logout;

    location / {
        proxy_pass http://127.0.0.1:3080;
    }
}
posted @ 2026-09-04 01:08  Akvicor  阅读(40)  评论(1)    收藏  举报