背景说明
研发有个需求,访问公司某个域名下的某个url时候需要认证,只有输入正确的用户密码才允许访问web内容。
实现思路
Nginx服务中的”ngx_http_auth_basic_module”模块可以实现此要求,默认情况下编译安装完nginx后,就已经安装启用了ngx_http_auth_basic_module模块,如果不需要这个模块,可以加上 –without-http_auth_basic_module关闭。
ngx_http_auth_basic_module模块指令:
语法: auth_basic string | off;
默认值: auth_basic off;
作用:默认表示不开启认证,后面如果跟上字符,这些字符会在弹窗中显示。
配置段: http, server, location, limit_except
语法: auth_basic_user_file file;
默认值: 无
作用:指定密码文件的位置,可以是相对路径或者绝对路径
配置段: http, server, location, limit_except
实现过程
下面以我的网站www.jiagoumi.com来演示此功能的实现过程,需求是仅当访问http://www.jiagoumi.com/test/时候输入密码才能访问
1. 使用openssl生成密码文件
# printf "test:$(openssl passwd -crypt 123123)n" >> /usr/local/nginx/conf/htpasswd.auth
[root@160719 nginx]# cat /usr/local/nginx/conf/htpasswd
test:bFJVr/zQWK60.
2.修改虚拟主机配置文件
下面红色部分为添加实现的代码
server {
listen 80;
server_name www.jiagoumi.com;
access_log logs/www.jiagoumi.com.access.log;
error_log logs/www.jiagoumi.com.error.log;
location /test {
auth_basic "Authorization Required";
auth_basic_user_file /usr/local/nginx/conf/htpasswd.auth;
index index.php index.html index.htm;
root /data/nginx/site/www.jiagoumi.com;
}
location /
{
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://192.168.1.1:8080;
}
验证配置文件,重启Nginx服务:
# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/nginx.conf test is successful
# /usr/local/nginx/sbin/nginx -s reload
3.验证效果
访问http://www.jiagoumi.com/test/会提示输入密码,输入上面创建的账号密码即可登录查看内容。
注意:此功能需要使用IE兼容模式访问,使用chrome内核的浏览器无法正常访问。