nginx访问控制配置

nginx的访问控制

一、基于IP的访问控制(ngx_http_access_module)

该模块允许限制访问某些客户端地址。配置文件如下:

location ~ ^/index.html {
        root   /app;  
        deny all;
        allow 127.0.0.1;
        index  index.html index.htm;
    }

其中~表示对请求路径url的模式匹配,其中root后面的路径就是index.html在根目录以下的路径,该配置的意思是/app下的index.html文件只允许本地访问。

若是只对某些ip网段设置黑名单,配置如下:

location ~ ^/index.html {
        root   /app;  
        deny 192.168.1.0/24;192.168.0.0/16;
        allow all;
        index  index.html index.htm;
    }

若是想禁止访问所有目录下的sql|log|txt|jar|war|sh|py后缀的文件,配置如下:
location ~.*.(sql|log|txt|jar|war|sh|py) {
deny all;
}
配置完成后记得检查配置重启,命令如下:

nginx -tc /etc/nginx/nginx.conf 
systemctl reload nginx

ngx_http_access_module 的局限性

当客户端通过代理访问时,nginx的remote_addr(获取的是直接和服务器建立连接的客户端ip)获取的就是代理的ip。所以就需要使用http_x_forwarded_for(可以记录客户端及中间件代理的ip)

二、基于用户认证的访问控制 (ngx_http_auth_basic_module)

该模块允许使用“HTTP基本认证协议”验证用户名和密码来限制对资源的访问,

在编辑配置文件前,需要创建保存用户名和密码的文件user_file,文件格式如下:

name1:password1
name2:password2

密码加密选择的是htpasswd。所以在创建该文件前,需要安装加密对应的包,命令如下:

yum -y install httpd-tools

创建user_file:

htpasswd -c -m /var/users cuicui qazwsx

编辑配置文件:

扫描二维码关注公众号,回复: 6160398 查看本文章
location ~ ^/index.html {
        root   /app;
    auth_basic "Auth access test! input your password!";
    auth_basic_user_file  /var/users;
        index  index.html index.htm;
    }

配置完成后记得检查配置重启,命令如下:

nginx -tc /etc/nginx/nginx.conf 
systemctl reload nginx

猜你喜欢

转载自blog.csdn.net/m0_37711941/article/details/89945886