之前在爆Zabbix漏洞的时候,在未进行漏洞升级修复的情况下,可以先对nginx的web入口加一个认证,这样就能很大程度上降低被黑的风险。同理在使用Nginx代理一些服务的时候,也可以用这种方法进行安全上的加固。做起来比较简单,却行之有效。Nginx上一般使用的认证方式有2种,分别是auth_basic(本机认证)及ngx_http_auth_request_module(第三方认证)
auth_basic(本机认证)配置
- 如给web服务设置代理nginx配置文件如下
1 2 3 4 5 6 7 8 9 10 11 12 13
server { listen 7777; server_name 127.0.0.1; auth_basic "test-web"; auth_basic_user_file /usr/local/nginx/testweb.db; location / { proxy_pass http://11.11.11.5:80; proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } #charset koi8-r; }
- 创建登录密码文件
1 2
#可以使用htpasswd,或者使用openssl printf "taiyouxi:$(openssl passwd -crypt YourPassword)\n" >/usr/local/nginx/testweb.db
- 设置说明:
–开启认证– 默认值: auth_basic off; 语法: auth_basic string | off; 如使用auth_basic “test-web”;会在弹窗上显示test-web的字样 –密码文件说明– 语法: auth_basic_user_file file; 配置段: http, server, location, limit_except
ngx_http_auth_request_module(第三方认证)配置
由于这个模块并不属于内置模块,默认使用yum安装是不会带这个模块的,可以下载源码重新带上这个模块编译安装。
- 原yum默认编译参数查看
|
|
- 先源码安装nginx
1 2 3 4 5 6 7 8
yum -y install gcc gcc-c++ make libtool zlib zlib-devel openssl openssl-devel pcre pcre-devel wget http://nginx.org/download/nginx-1.10.3.tar.gz tar xvf nginx-1.10.3.tar.gz git clone git://github.com/perusio/nginx-auth-request-module.git cd nginx-1.10.3 ./configure --prefix=/usr/local/nginx --add-module=../nginx-auth-request-module make make install
- 测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
server { listen 20010; server_name 127.0.0.1; location / { auth_request /auth; proxy_pass http://127.0.0.1:80; proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; #charset koi8-r; } location = /auth { proxy_pass http://127.0.0.1:80/passwd/HttpBasicAuthenticate.php; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; } }
- php认证代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#vim html/passwd/HttpBasicAuthenticate.php <?php if(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){ $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; if ($username == 'wang' && $password == '123456'){ return true; } } header('WWW-Authenticate: Basic realm="Git Server"'); header('HTTP/1.0 401 Unauthorized'); ?>
- 说明
用户访问server 弹出框中输入的用户名、密码保存在 $_SERVER 变量中 中间 if 段,只做演示用实际中应该是拿用户输入的用户名、密码跟数据库中的数据做比较 参考:http://www.cnblogs.com/wangxiaoqiangs/p/6184181.html