为何修改Nginx用户与组?
-
Nginx运行时进程需要有用户与组的支持,以实现对网站文件读取时进行访问控制
-
Nginx默认使用 nobody用户账号与组账号,一般也要进行修改
-
修改的方法
编译安装时指定用户与组
修改配置文件时指定用户与组
开启和关闭Nginx
[root@localhost nginx]# cd /usr/local/nginx/
[root@localhost sbin]# nginx 开启nginx
[root@localhost sbin]# killall -s QUIT nginx 关闭进程
查看端口是否开启
[root@localhost nginx]# netstat -ntap | grep 80 查看监听地址
[root@localhost nginx]# yum install -y elinks 检查
[root@localhost sbin]# elinks http://localhost 查看是否开启
启用HTTP_STUB_STATUS状态统计模块
[root@localhost ~]# tar zxvf nginx-1.12.2.tar.gz
[root@localhost ~]#cd /opt
[root@localhost opt]# yum install -y gcc gcc-c++ pcre-devel zlib-devel
[root@localhost nginx-1.12.2]# ./configure \ 启动脚本
--prefix=/usr/local/nginx \ 配置安装路径
--user=nginx \ 指定用户
--group=nginx \ 指定组
--with-http_stub_status_module 开启统计模块
make && make install
[root@localhost nginx-1.12.2]# ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/
[root@localhost nginx]# cd /usr/local/nginx/
[root@localhost nginx]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/ 创建软链接让系统可以识别
修改nginx配置文件
[root@localhost nginx-1.12.2]# vim /usr/local/nginx/conf/nginx.conf ## 编辑配置文件
添加如下内容:
location /status {
stub_status on;
access_log off;
}
开启nginx服务
[root@localhost nginx-1.12.2]# nginx
在浏览器中输入地址进行访问统计页面
http://192.168.136.88/status
授权的访问控制
[root@localhost nginx]# vim /usr/local/nginx/conf/nginx.conf
43 location / {
44 auth_basic "secret";
45 auth_basic_user_file /user/local/nginx/passwd.db;
设置用户名和密码
[root@localhost nginx]# yum -y install httpd-tools
[root@localhost nginx]# htpasswd -c /usr/local/nginx/passwd.db zhang
New password: ## 输入密码
Re-type new password: ## 确认密码
Adding password for user zhang
[root@localhost nginx]# cd /usr/local/nginx/
[root@localhost nginx]# nginx
[root@localhost nginx]# iptables -F
[root@localhost nginx]# setenforce 0
[root@localhost nginx]# systemctl stop firewalld
3、修改认证文件的属主
[root@localhost nginx-1.12.2]# chown nginx /usr/local/nginx/passwd
4、修改认证文件权限
[root@localhost nginx-1.12.2]# chmod 400 /usr/local/nginx/passwd
5、编辑nginx配置文件
[root@localhost nginx-1.12.2]# vim /usr/local/nginx/conf/nginx.conf
## 在虚拟主机的location字段中添加如下两行:
auth_basic "secret";
auth_basic_user_file /usr/local/nginx/passwd;
6、打开浏览器,清除缓存并重启,输入192.168.136.88进行访问
只要输入之前用htpasswd工具生成的用户名和密码就可以登录正常访问页面了
基于客户端IP实现访问控制
1、修改nginx配置文件,在虚拟主机中添加拒绝地址名单
[root@localhost nginx-1.12.2]# vim /usr/local/nginx/conf/nginx.conf ## 编辑配置文件
server {
server_name 192.168.50.134;
location / {
deny 192.168.136.100; ## 拒绝IP地址为192.168.50.136地址的主机访问
allow all; ## 允许其他所有主机访问
root /var/www/test;
index index.html index.php;
}
}
2、重启nginx服务
[root@localhost conf]# systemctl restart nginx
3、使用客户机(IP:192.168.136.100)进行访问,打开浏览器,清空缓存后重启,访问192.168.50.134
从看出已经不能访问了