最新消息:

Nginx配置-非特定IP需要输入密码才能访问

Linux ipcpu 1398浏览 0评论

Nginx配置,非特定IP需要输入密码才能访问.md

需求

有一个后台站点,仅允许公司的外网IP可以访问,这样的话,在nginx中使用allow、deny就可以实现,如果前面还有CDN或者负载均衡器,也可以使用$http_x_forwarded_for参数来进行判断;
今天又来了一个新需求,假如用户不是在公司,而是在家里也想访问,但又不想拨VPN,咋办?
可以让这些用户输入一层密码来进行保护。
总结起来就是,指定IP(公司外网IP)能直接打开,非指定IP需要输入密码才能打开。

实现

    location / {
        proxy_pass http://test;

        #auth while from internet
        set $auth_basic off;

         if ( $http_x_forwarded_for !~ "223.21.230.186|112.134.186.(25[0-5]|2[0-4][0-9]|1[0-9]\{2\}|[1-9][0-9]|[0-9])") {       
            set $auth_basic Restricted;   
        }

        auth_basic $auth_basic;
        auth_basic_user_file htpasswd;

    }

不能直接在if中写auth_basic,会报错"nginx: [emerg] "auth_basic" directive is not allowed here"

 if ( $http_x_forwarded_for !~ "223.21.230.186|104.30.235.2") {
        auth_basic "abcdef";
        auth_basic_user_file htpasswd;
}
来自为知笔记(Wiz)

转载请注明:IPCPU-网络之路 » Nginx配置-非特定IP需要输入密码才能访问

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址