Nginx控制访问

nginx配置文件操作


Nginx访问控制

用于http, server, location, limit_except段
allow:设定允许哪台或哪些主机访问
deny:设定禁止哪台或哪些主机访问

示例:

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location / {
        allow 192.168.188.1;            //仅允许这个IP访问
        deny all;                       //拒绝所有主机访问
        }
......

[root@nginx ~]# systemctl restart nginx.service
[root@nginx ~]# curl 127.0.0.1  //连本机都访问不了了
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>

Nginx用户认证

应用于http, server, location, limit_except段
配置如下:

auth_basic "欢迎信息";
auth_basic_user_file "/path/to/user_auth_file"

示例:

#首先要下载httpd-tools软件包
[root@nginx ~]# dnf -y install httpd-tools

#生成密码隐藏文件.usr_auth_file,用alg用户登录
[root@nginx ~]# htpasswd -c -m /usr/local/nginx/conf/.usr_auth_file alg
New password:
Re-type new password:
Adding password for user alg

#密码文件格式
[root@nginx ~]# cat /usr/local/nginx/conf/.usr_auth_file
alg:$apr1$SRxq3BmN$X6B03xjksa79gdF7AdFub.

#修改配置文件,开启用户认证
        location = /zjq {
        auth_basic "hello";
        auth_basic_user_file /usr/local/nginx/conf/.usr_auth_file;
        echo "123";
        }

#重启服务去网页访问
[root@nginx ~]# systemctl restart nginx.service

访问效果

在这里插入图片描述

在这里插入图片描述

https配置

#生成私钥,生成证书签署请求并获得证书
[root@nginx ~]# mkdir /etc/pki/CA
[root@nginx ~]# cd /etc/pki/CA
[root@nginx CA]# mkdir private
[root@nginx CA]# mkdir certs newcerts crl
[root@nginx CA]# touch index.txt && echo 01 > serial
[root@nginx CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
....................................+++++
.+++++
e is 65537 (0x010001)
[root@nginx CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:runtime
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:www.nanhu.com
Email Address []:1@2.com
[root@nginx CA]#
[root@nginx CA]# cd private/
[root@nginx private]# mkdir certs newcerts crl
[root@nginx private]# ls
cakey.pem  certs  crl  newcerts
[root@nginx private]# touch index.txt && echo 01 > serial
[root@nginx private]# cd /usr/local/nginx/conf/ && mkdir ssl && cd ssl
[root@nginx ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
........+++++
............................+++++
e is 65537 (0x010001)

[root@nginx ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:runtime
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:www.nanhu.com
Email Address []:1@2.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@nginx ssl]# ls
nginx.csr  nginx.key

[root@nginx ssl]# openssl ca -in /usr/local/nginx/conf/ssl/nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 13 15:39:28 2022 GMT
            Not After : Oct 13 15:39:28 2023 GMT
        Subject:
            countryName               = cn
            stateOrProvinceName       = hb
            organizationName          = runtime
            organizationalUnitName    = linux
            commonName                = www.nanhu.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                11:0C:6D:68:EA:47:7F:49:2E:68:66:1A:89:19:94:5D:F6:B5:CA:D8
            X509v3 Authority Key Identifier:
                keyid:48:88:97:C4:2B:99:CC:19:A6:09:7A:23:17:FB:E3:5E:34:C7:A0:67

Certificate is to be certified until Oct 13 15:39:28 2023 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

#在nginx.conf中配置如下内容(取消下面内容注释):
[root@nginx ssl]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      ssl/nginx.crt;  //修改这行配置
        ssl_certificate_key  ssl/nginx.key;  //修改这行配置

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
[root@nginx ssl]# systemctl restart nginx.service

访问测试
在这里插入图片描述

开启状态界面

访问状态页面的方式:http://server_ip/status

状态码表示的意义
Active connections当前所有处于打开状态的连接数
accepts总共处理了多少个连接
handled成功创建多少握手
requests总共处理了多少个请求
Readingnginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writingnginx返回给客户端的Header信息数,表示请求已经接收完成,且正处于处
Waiting开启keep-alive的情况下,这个值等于active - (reading + writing),意思就

配置如下

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
        location /status {
            stub_status on;
            allow 192.168.188.0/24;
            deny all;
        }
[root@nginx ~]# systemctl restart nginx.service

在这里插入图片描述

rewrite

语法:rewrite regex replacement flag;

应用场景:

  • server字段
  • location字段
  • if字段
//如:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
 
//此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

如上例所示,replacement可以是某个URI,也可以是某个URL

  • 常见的flag
flag作用
last基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break中止Rewrite,不再继续匹配一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求,且不再会被当前server内的任何rewrite规则所检查
redirect以临时重定向的HTTP状态302返回新的URL
permanent以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:

标识符意义
^必须以^后的实体开头
$必须以$前的实体结尾
.匹配任意字符
*匹配其前面的任意单个字符任意次
.*任意长度的任意字符
[]匹配指定字符集内的任意单个字符
[^]匹配任何不包括在指定字符集内的任意字符串
|匹配
()分组,组成一组用于匹配的实体,通常会有

示例重写URI

#上传一张图片到/usr/local/nginx/html
[root@nginx ~]# cd /usr/local/nginx/html
[root@nginx html]# ls
50x.html  dog.jpg  index.html

#当访问以images开头后面是"/"任何东西的URI时,我们重写URI为,/photo/$1
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location /images {
        rewrite ^/images/.*\.jpg /photo/$1 break ;
        }
......
[root@nginx ~]# systemctl reload nginx.service

在这里插入图片描述

#当访问以bbs开头后面是"/"任何东西的URI时,重写URL为https://gitee.com/explore
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location /bbs{
            rewrite ^/bbs/(.*)$ https://gitee.com/explore/bbs break;
        }
......
[root@nginx ~]# systemctl reload nginx.service

在这里插入图片描述

在这里插入图片描述

#要写两个location,因为第一个匹配到了之后就不会被同一个location下的其他rewrite所匹配到
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location /images {
            rewrite ^/images/(.*\.png)$ /photo/$1 last;
        }
        location /photo {
            rewrite ^/photo/(.*)$ http://www.baidu.com break;
        }
.......
[root@nginx ~]# systemctl reload nginx.service

输入路径直接跳转到百度页面
在这里插入图片描述
这里图片显示不出来,不知道为什么显示图片违规,这里显示的应该是百度的界面
在这里插入图片描述

#permanent	以永久重定向的HTTP状态301返回新的URL
[root@nginx conf]# vim /usr/local/nginx/conf/nginx.conf  
  		location /images {
            rewrite ^/images/(.*\.jpg)$ /dog/$1 permanent;
        }
[root@nginx conf]# curl 127.0.0.1/images/dog.jpg
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>

#redirect	以临时重定向的HTTP状态302返回新的URL
[root@nginx conf]# vim /usr/local/nginx/conf/nginx.conf  
		location /images {
            rewrite ^/images/(.*\.jpg)$ /dog/$1 redirect;
        }

[root@nginx conf]# curl 127.0.0.1/images/dog.jpg
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>

if

语法:if (condition) {...}

应用场景:

  • server段
  • location段

常见的condition

  • 变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
  • 以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
  • 正则表达式的模式匹配操作
    • ~:区分大小写的模式匹配检查
    • ~*:不区分大小写的模式匹配检查
    • !~和!~*:对上面两种测试取反
  • 测试指定路径为文件的可能性(-f,!-f)
  • 测试指定路径为目录的可能性(-d,!-d)
  • 测试文件的存在性(-e,!-e)
  • 检查文件是否有执行权限(-x,!-x)

基于浏览器实现分离案例

if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}

防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}

反向代理与负载均衡

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。

nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了。

但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储。

Http Proxy模块,功能很多,最常用的是proxy_pass和proxy_cache

如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:
./configure --add-module=…/ngx_cache_purge-1.0 …

nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内

在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如:

upstream idfsoft.com {
  ip_hash;
  server 127.0.0.1:9080 weight=5;
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}

注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,翻墙等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。

定义好upstream后,需要在server段内添加如下内容:

server {
  location / {
    proxy_pass http://idfsoft.com;
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随便投投

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值