3.12 nginx安装及使用

1. nginx升级、添加模块

//查看当前版本
[root@130 nginx-1.16.1]# nginx -V					
nginx version: nginx/1.12.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

//备份当前版本
[root@130 nginx-1.16.1]# cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx-1.12
[root@130 nginx-1.16.1]# ls /usr/local/nginx/sbin/
nginx  nginx-1.12

//升级版本
[root@130 ~]# cd nginx-1.16.1
[root@130 nginx-1.16.1]# ls ..
anaconda-ks.cfg  nginx-1.16.1.tar.gz            nginx-http-echo-module-master.zip
nginx-1.16.1     nginx-http-echo-module-master  pass
[root@130 nginx-1.16.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@130 nginx-1.16.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../nginx-http-echo-module-master
[root@130 nginx-1.16.1]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@130 nginx-1.16.1]# make

//停止现有nginx服务
[root@130 nginx-1.16.1]# nginx -s stop
[root@130 nginx-1.16.1]# ss -anlt
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128             *:22                          *:*                  
LISTEN      0      128     127.0.0.1:9000                        *:*                  
LISTEN      0      128            :::22                         :::*                  
LISTEN      0      80             :::3306                       :::*

//升级nginx
[root@130 nginx-1.16.1]# ls objs/
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src
[root@130 nginx-1.16.1]# cp objs/nginx /usr/local/nginx/sbin/.
cp:是否覆盖"/usr/local/nginx/sbin/./nginx"? y
[root@130 nginx-1.16.1]# nginx
[root@130 nginx-1.16.1]# nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../nginx-http-echo-module-master

2. nginx日志log定义格式

log_format 定义日志格式

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
access_log  logs/access.log  main;

//注意:此处可用变量为nginx各模块内建变量

3.location使用

location区段,通过指定模式来与客户端请求的URI相匹配

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能

//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

修饰符 功能
= 精确匹配
~ 正则表达式模式匹配,区分大小写
~* 正则表达式模式匹配,不区分大小写
^~ 前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@ 定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

3.1 无修饰符

没有修饰符表示必须以指定模式开始,如:

server {
  server_name www.idfsoft.com;
  location /abc {
    ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
  • http://www.idfsoft.com/abc/
    示例:
[root@130 conf]# vim nginx.conf
    	location /abc {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/abc?a=1\&b=2
haha
[root@130 conf]# curl http://192.168.80.130/abc/
haha

3.2 = 使用方法

=:表示必须与指定的模式精确匹配,如:

server {
  server_name www.idfsoft.com;
  location = /abc {
    ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
    如下内容则无法匹配:
  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abc/abcde
    示例:
[root@130 conf]# vim nginx.conf
    	location = /abc {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/abc?a=1\&b=2
haha
[root@130 conf]# curl http://192.168.80.130/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

3.3 ~ (指定正则表达式区分大小写匹配)

~:表示指定的正则表达式要区分大小写,如:

server {
  server_name www.idfsoft.com;
  location ~ ^/abc$ {
  ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
    如下内容则无法匹配:
  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/ABC
  • http://www.idfsoft.com/abcde
  • 示例:
[root@130 conf]# vim nginx.conf
    	location ~ ^/abc$ {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
[root@130 conf]# curl http://192.168.80.130/ABC
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

3.4 ~* (指定的正则表达式不区分大小写匹配)

~*:表示指定的正则表达式不区分大小写,如:

server {
  server_name www.idfsoft.com;
  location ~* ^/abc$ {
    ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
  • http://www.idfsoft.com/ABC
    如下内容则无法匹配:
  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abcde

示例:

[root@130 conf]# vim nginx.conf
    	location ~ ^/abc$ {
            root html;
            echo 'haha\n';
        }
[root@130 conf]# nginx -s reload
[root@130 conf]# curl http://192.168.80.130/abc
haha
[root@130 conf]# curl http://192.168.80.130/ABC
haha
[root@130 conf]# curl http://192.168.80.130/abc/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式

3.5 location查找顺序和优先级

查找顺序和优先级:由高到底依次为

  1. 带有=的精确匹配优先
  2. 正则表达式按照他们在配置文件中定义的顺序
  3. 带有^~修饰符的,开头匹配
  4. 带有*修饰符的,如果正则表达式与URI匹配
  5. 没有修饰符的精确匹配

优先级次序如下:

( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

4. 访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数需另起一行,以“;”结束
deny:设定禁止哪台或哪些主机访问,多个参数需另起一行,以“;”结束
示例:

location  / {
      root   html/zabbix;
      index  index.php index.html;
      allow 192.168.80.0/24;
      allow 192.168.80.1/32;
      deny all;
}

5. 基于用户认证

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

user_auth_file内容格式为:

username:password

这里的密码为加密后的密码串,建议用htpasswd来创建此文件:

htpasswd -c -m /path/to/.user_auth_file USERNAME

示例:

[root@130 ~]# htpasswd -c -m /usr/local/nginx/conf/userfile/.user_auth_file yusy
New password: 
Re-type new password: 
Adding password for user yusy
[root@130 ~]# vim /usr/local/nginx/conf/nginx.conf
      location  / {
            root   html/zabbix;
            index  index.php index.html;

            auth_basic "welcome to zabbix";
            auth_basic_user_file "/usr/local/nginx/conf/userfile/.user_auth_file";
      }
[root@130 ~]# nginx -s reload

效果:
在这里插入图片描述

6. 开启状态界面

开启status:

location /status {
  stub_status {on | off};
  allow 192.168.80.1/32;
  deny all;
}

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

状态页面信息详解:

状态码 表示的意义
Active connections 2 当前所有处于打开状态的连接数
accepts 总共处理了多少个连接
handled 成功创建多少握手
requests 总共处理了多少个请求
Reading nginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writing nginx返回给客户端的Header信息数,表示请求已经接收完成,且正处于处理请求或发送响应的过程中的连接数
Waiting 开启keep-alive的情况下,这个值等于active - (reading +writing),意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

7. zabbix监控网站

写脚本监控nginx状态

[root@130 scripts]# cat nginx-accept.sh 
#/bin/bash
status=$(curl http://192.168.80.130/status 2>/dev/null |awk 'NR==3{print $1}')
echo $status
[root@130 scripts]# cat nginx-request.sh 
#/bin/bash
status=$(curl http://192.168.80.130/status 2>/dev/null |awk 'NR==3{print $3}')
echo $status

[root@130 scripts]# vim /usr/local/etc/zabbix_agentd.conf
UnsafeUserParameters=1

UserParameter=nginx-accept,/bin/bash /scripts/nginx-accept.sh
UserParameter=nginx-request,/bin/bash /scripts/nginx-request.sh

zabbix添加监控项
1.点击监控项
在这里插入图片描述
2.添加监控项
在这里插入图片描述
3.添加监控事件
在这里插入图片描述
在这里插入图片描述
查看监控事件
在这里插入图片描述
在这里插入图片描述

8. rewrite

语法:rewrite regex replacement flag;,如:

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

此处的$1用于引用(.*.jpg)匹配到的内容,又如:

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

示例:
1. 初始路径

[root@130 nginx]# ls html/images/
1.jpg
[root@130 nginx]# vim conf/nginx.conf
	location  /images {
        root html;
    }

在这里插入图片描述
修改路径后,为保证原路径依然可用使用rewrite重写访问到原网站或原路径

[root@130 nginx]# vim conf/nginx.conf
	    location  /images {
            root html;
        }
        location /imgs {
            rewrite ^/imgs/(.*)$ /images/$1 break;
        }
[root@130 nginx]# nginx -s reload

在这里插入图片描述
跳转到其它URL

[root@130 nginx]# vim conf/nginx.conf
	location /imgs {
            rewrite ^/imgs/(.*)$ http://www.baidu.com break;
        }
[root@130 nginx]# nginx -s reload        

在这里插入图片描述
在这里插入图片描述
如上例所示,replacement可以是某个路径,也可以是某个URL

常见的flag

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

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

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

标识符 意义
^ 必须以^后的实体开头
$ 必须以$前的实体结尾
. 匹配任意字符
[] 匹配指定字符集内的任意字符
[^] 匹配任何不包括在指定字符集内的任意字符串
| 匹配| 之前或之后的实体
() 分组,组成一组用于匹配的实体,通常会有 | 来协助

捕获子表达式,可以捕获放在()之间的任何文本,比如:

^(hello|sir)$       //字符串为“hi sir”捕获的结果:$1=hi$2=sir

//这些被捕获的数据,在后面就可以当变量一样使用了

9. if

语法:if (condition) {…}
应用场景:

  • server段
  • location段

常见的condition

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

10. 基于浏览器实现分离案例

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;
}

11. 防盗链案例

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

12. 反向代理和负载均衡

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

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

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

Http Proxy模块,功能很多,最常用的是proxy_passproxy_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;			//利用hash算法使客户端在一段时间内固定访问一台web服务器
  server 127.0.0.1:9080 weight=5;	//weight指定该web服务器允许被一个客户端访问次数,达到次数则替换为访问下一台web服务器
  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;
  }
}

示例:

//web服务器防火墙均需要关闭
systemctl disable firewalld
systemctl stop firewalld
setenforce 0

//配置web服务器128
[root@128 ~]# yum -y install httpd
[root@128 ~]# vim /etc/httpd/conf/httpd.conf
ServerName www.example.com:80
[root@128 html]# echo 'this 128: hello'>/var/www/html/index.html
[root@128 html]# systemctl restart httpd
[root@128 html]# ss -anlt
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128             *:111                         *:*                  
LISTEN      0      128             *:22                          *:*                  
LISTEN      0      100     127.0.0.1:25                          *:*                                  
LISTEN      0      128            :::80                         :::*      

//配置web服务器131
[root@131 ~]# yum -y install httpd
[root@131 ~]# vim /etc/httpd/conf/httpd.conf
ServerName www.example.com:80
[root@131 ~]# echo 'this 131: hello'>/var/www/html/index.html
[root@131 ~]# systemctl restart httpd
[root@131 ~]# ss -anlt
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128             *:22                          *:*                  
LISTEN      0      50              *:3306                        *:*                  
LISTEN      0      128            :::80                         :::*                  
LISTEN      0      128            :::22                         :::*

//配置nginx代理
[root@130 conf]# vim nginx.conf
	upstream yy.com{
       	server 192.168.80.128;
       	server 192.168.80.131;
	}
	server {
        listen       80;
        server_name  localhost;
		
        location / {
            proxy_pass http://yy.com;
        }
[root@130 conf]# 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@130 conf]# nginx -s reload           

点击刷新可看到页面由不同web服务器提供,实现了负载轮询

在这里插入图片描述
在这里插入图片描述

发布了50 篇原创文章 · 获赞 8 · 访问量 1885

猜你喜欢

转载自blog.csdn.net/Yusyang_/article/details/103795803