Nginx配置用户名密码访问
在 Nginx 下,提供了 ngx_http_auth_basic_module 模块实现让用户只有输入正确的用户名密码才允许访问web内容。默认情况下,Nginx 已经安装了该模块。所以整体的一个过程就是先用第三方工具设置用户名、密码(其中密码已经加过密),然后保存到文件中,接着在 Nginx 配置文件中根据之前事先保存的文件开启访问验证。
生成密码可以使用 htpasswd,或者使用 openssl 。下面以 htpasswd 为例。
一、安装htpassed工具
- 通过YUM安装httpd-tools
[root@localhost ~]# yum -y install httpd-tools
- 设置用户名和密码,并把用户名、密码保存到指定文件中:
[root@localhost ~]# mkdir /usr/local/nginx/auth [root@localhost ~]# htpasswd -c /usr/local/nginx/auth/passwd admin
注意:/usr/local/nginx/auth/passwd是生成密码后的文件保存路径(passwdfile),admin是用户名(username)
查看最后生成的密码文件的内容:(admin分号后的内容就是加密过的密码)[root@localhost ~]# cat /usr/local/nginx/auth/passwd admin:$apr1$YiiyRyOe$C7voJqf8XHqsneZpbuI.31
二、修改配置文件
-
编辑Nginx配置文件,在对应的站点server段加入以下内容
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf server { listen 80 default_server; listen [::]:80 default_server; server_name _; auth_basic "Please input password";#这里是验证时的提示信息 auth_basic_user_file /usr/local/nginx/auth/passwd; root /srv/serverstatus/web/; index index.html index.htm index.nginx-debian.html; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } }
-
重启Nginx服务
[root@localhost ~]# /usr/local/nginx/sbin/nginx -t nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful [root@localhost ~]# /usr/local/nginx/sbin/nginx -s reload
-
验证
浏览器访问服务器IP,出现登录界面
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。