03.Nginx常用模块

1.Nginx下载站点

Nginx默认是不允许列出整个目录浏览下载。

Syntax: autoindex on | off;Default:    
autoindex off;Context:    http, server, location//autoindex常用参数
autoindex_exact_size off;
默认为on, 显示出文件的确切大小,单位是bytes。
修改为off,显示出文件的大概大小,单位是kB或者MB或者GB。

autoindex_localtime on;
默认为off,显示的文件时间为GMT时间。
修改为on, 显示的文件时间为文件的服务器时间。

charset utf-8,gbk;
默认中文目录乱码,添加上解决乱码。

配置目录浏览功能

//开启目录浏览
location / {
    root html;
    autoindex on;
    autoindex_localtime on;
    autoindex_exact_size off;
}

2.Nginx状态监控

ngx_http_stub_status_module展示Nginx连接状态信息

Nginx编译时需加入该参数--with-http_stub_status_module

Syntax: stub_status;Default:    —Context:    server, location

配置Nginx status

 location /mystatus {
    stub_status;
    access_log off;
}

2.访问后得到的结果

Active connections:2    #当前活动的连接数server accepts handled requests16     16     1916          # 总连接数connection16          # 成功的连接数connection(失败连接=(总连接数-成功连接数))19          # 总共处理的请求数requests# connection 连接数, tcp连接数# requests  http请求数, GET/POST/DELETE/UPLOAD# keepalive_timeout 0;  每次连接都会产生一次请求(短连接)# keepalive_timeout 60; 在60s以内的请求建立在一个连接基础之上(长连接)Reading:2 Writing:1 Waiting: 19Reading             #请求Writing             #响应Waiting             #等待的请求数,开启了keepalive

3.Nginx访问控制

基于IP的访问控制 http_access_module
基于用户登陆认证 http_auth_basic_module

2.Nginx基于IP的访问控制

//允许配置语法Syntax: allow address | CIDR | unix: | all;Default:    —
Context:    http, server, location, limit_except//拒绝配置语法Syntax: deny address | CIDR | unix: | all;Default:    —
Context:    http, server, location, limit_except

访问控制配置示例

# 配置拒绝某一个IP, 其他全部允许location ~ ^/1.html {    root /usr/share/nginx/html;    index index.html;    deny 192.168.56.1;    allow all;
}# 只允许某一个网段访问,其它全部拒绝location / {    root   html;    index  index.php index.html index.htm;    allow   192.168.56.0/24;    deny    all;
}

http_access_module局限性

下图是使用http_x_forwarded_for记录真实客户端IP地址以及代理服务器IP

解决方式
1.采用HTTP头信息控制访问, 代理以及web服务开启http_x_forwarded_for
2.结合geo模块作
3.通过HTTP自动以变量传递

基于用户登陆认证

//配置语法Syntax: auth_basic string| off;Default:    auth_basic off;
Context:    http, server, location, limit_except//用户密码记录配置文件Syntax: auth_basic_user_file file;Default:    -
Context:    http, server, location, limit_except//需要安装依赖组件[root@xuliangwei ~]# yum install httpd-tools[root@xuliangwei ~]# htpasswd -c /etc/nginx/auth_conf xuliangwei//可在http,server,location下添加如下信息auth_basic "Auth access Blog Input your Passwd!";
auth_basic_user_file /etc/nginx/auth_conf;

用户认证局限性
1.用户信息依赖文件方式
2.用户管理文件过多, 无法联动
3.操作管理机械,效率低下

解决办法
1.Nginx结合LUA实现高效验证
2.Nginx结合LDAP利用nginx-auth-ldap模块

4.Nginx访问限制

经常会遇到这种情况,服务器流量异常,负载过大等等。对于大流量恶意的攻击访问, 会带来带宽的浪费,服务器压力,影响业务,往往考虑对同一个ip的连接数,并发数进行限制。 
ngx_http_limit_conn_module模块可以根据定义的key来限制每个键值的连接数,如同一个IP来源的连接数。

limit_conn_module 连接频率限制
limit_req_module 请求频率限制

http协议的连接与请求

HTTP是建立在TCP, 在完成HTTP请求需要先建立TCP三次握手(称为TCP连接),在连接的基础上在HTTP请求。



HTTP请求建立在一次TCP连接基础上,一次TCP请求至少产生一次HTTP请求

注:客户端的IP地址作为键。

$remote_addr 变量的长度为7字节到15字节 
$binary_remote_addr 变量的长度是固定的4字节

如果共享内存空间被耗尽,服务器将会对后续所有的请求返回 503错误 (Service Temporarily Unavailable)

1.Nginx连接限制配置

//Nginx连接限制语法Syntax:  limit_conn_zone key zone=name:size;Default: —
Context: http

Syntax: limit_conn zone number;Default: —
Context: http, server, location//具体配置如下:http {//http段配置连接限制, 同一时刻只允许一个客户端IP连接limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
    ...
    server {
    ...  

        location / {        //同一时刻只允许一个客户端IP连接
            limit_conn conn_zone 1;
        }//压力测试yum install -y httpd-tools
ab -n 50 -c 20  http://127.0.0.1/index.html

2.Nginx请求限制配置

//Nginx请求限制语法Syntax:  limit_req_zone key zone=name:size rate=rate;Default: —
Context: http

Syntax: limit_conn zone number [burst=number] [nodelay];Default: —
Context: http, server, location//具体配置如下:http {//http段配置请求限制, rate限制速率,限制一秒钟最多一个IP请求limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
    ...
    server {
    ...  

        location / {        //1r/s只接收一个请求,其余请求拒绝处理并返回错误码给客户端
            limit_req zone=req_zone;        //请求超过1r/s,剩下的将被延迟处理,请求数超过burst定义的数量, 多余的请求返回503
            #limit_req zone=req_zone burst=3 nodelay;
        }//压力测试yum install -y httpd-tools
ab -n 50 -c 20  http://127.0.0.1/index.html

连接限制没有请求限制有效?

我们前面说过, 多个请求可以建立在一次的TCP连接之上, 那么我们对请求的精度限制,当然比对一个连接的限制会更加的有效。

因为同一时刻只允许一个连接请求进入。
但是同一时刻多个请求可以通过一个连接进入。
所以请求限制才是比较优的解决方案。

5.Nginx日志配置

在学习日志之前, 我们需要先了解下HTTP请求和返回

curl -v http://www.baidu.com

Nginx有非常灵活的日志记录模式。每个级别的配置可以有各自独立的访问日志。日志格式 通过log_format命令定义格式。

1.log_format指令

//配置语法: 包括: error.log access.logSyntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http

示例
name 表示格式名称 
string 表示定义的格式#默认Nginx语法示例log_format combined '$remote_addr - $remote_user [$time_local] '
 ' "$request" $status $body_bytes_sent '
 ' "$http_referer" "$http_user_agent" ';

Nginx日志配置规范

Syntax: log_format name [escape=default|json] string ...;Default:    log_format combined "...";Context:    http//Nginx默认配置log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                   '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';# Nginx日志格式允许包含的变量:$remote_addr, $http_x_forwarded_for #记录客户端IP地址$remote_user        # 记录客户端用户名称$request            # 记录请求的URL和HTTP协议$status             # 记录请求状态$body_bytes_sent    # 发送给客户端的字节数,不包括响应头的大小$bytes_sent         # 发送给客户端的总字节数$msec               # 日志写入时间。 单位为秒, 精度是毫秒。$http_referer       # 记录从哪个页面链接访问过来的$http_user_agent    # 记录客户端浏览器相关信息$request_length     # 请求的长度(包括请求行, 请求头和请求正文)。$request_time       # 请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始, 直到把最后一个字符发送给客户端后进行日志写入为止。$time_iso8601       # ISO8601标准格式下的本地时间。$time_local         # 通用日志格式下的本地时间。# 注:如果Nginx位于负载均衡器,nginx反向代理之后, web服务器无法直接获取到客 户端真实的IP地址。# $remote_addr获取的是反向代理的IP地址。 反向代理服务器在转发请求的http头信息中,# 增加X-Forwarded-For信息,用来记录客户端IP地址和客户端请求的服务器地址。

2.access_log指令

Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];access_log off;
Default: access_log logs/access.log combined;
Context: http, server, location, if in location, limit_except

gzip 压缩等级
buffer 设置内存缓存区大小flush 保存在缓存区中的最长时间
使用默认combined格式记录日志:access_log logs/access.log 或 access_log logs/access.log combined;

3.open_log_file_cache指令

对于每一条日志记录,都是先将文件打开, 再写入日志, 然后关闭。 
可以使用open_log_file_cache来设置日志文件缓存(默认是off), 格式如下:

Syntax: open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
Default:    open_log_file_cache off;
Context:    http, server, location

参数注释如下:
max: 设置缓存中的最大文件描述符数量,如果缓存被占满,采用LRU算法将描述符关闭
inactive: 设置存活时间,默认是10s
min_uses: 设置在inactive时间段内, 日志文件最少使用多少次后,该日志文件描述符记入缓存中,默认是1次
valid: 设置检查频率, 默认60s
off: 禁用缓存

示例:
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

6.Nginx虚拟主机

所谓虚拟主机,及在一台服务器上配置多个网站

如: 公司主页、博客、论坛看似三个网站, 实则可以运行在一台服务器上。

配置基于域名虚拟主机

1.创建web站点目录
[root@LNMP conf]# mkdir /soft/code/{www,bbs}[root@LNMP conf]# echo "www" > /soft/code/www/index.html[root@LNMP conf]# echo "bbs" > /soft/code/bbs/index.html2.配置虚拟主机
[root@LNMP conf]# cat conf.d/{www,bbs}.confserver {    listen       80;
    server_name  www.xuliangwei.com;
    root /soft/code/www;
    ...
}
 
server {
    ...    listen       80;
    server_name  bbs.xuliangwei.com;
    root /soft/code/bbs;
}

配置不同端口访问不同虚拟主机

//仅修改listen监听端口即可, 但不能和系统端口发生冲突
server {
    ...    listen       8001;
    ...
}
 
server {
    ...    listen       8002;
    ...
}

配置虚拟主机别名

所谓虚拟主机别名,就是虚拟主机设置除了主域名以外的一个域名,实现用户访问的多个域名对应同一个虚拟主机网站的功能。

以www.xuliangwei.com域名的虚拟主机为例:
为其增加一个别名xuliangwei.com时,出现网站内容和访问www.xuliangwei.com是一样的,具体配置如下:

//默认配置
[root@LNMP ~]# vim /etc/nginx/nginx.confserver {    listen       80;
    server_name www.xuliangwei.com;
}

//别名配置
[root@LNMP ~]# vim /etc/nginx/nginx.confserver {    listen       80;
    server_name  www.xuliangwei.com xuliangwei.com;
    ...
}

//使用Linux下curl测试结果
[root@LNMP conf]# curl xuliangwei.comwww.xuliangwei.com
[root@LNMP conf]# curl www.xuliangwei.comwww.xuliangwei.com

//访问带www和不带www是一样的, 除了别名实现也可以通过rewrite实现

2.Nginx多Server Server_name优先级

1.环境准备

[root@nginx ~]# mkdir /soft/code{1..3} -p[root@nginx ~]# for i in {1..3};do echo "<h1>Code $i</h1>" > /soft/code"$i"/index.html;done

2.准备多份相同Nginx配置文件

[root@Nginx conf.d]# ll总用量 12-rw-r--r-- 1 root root 123 4月  19 19:08 testserver1.conf
-rw-r--r-- 1 root root 123 4月  19 19:09 testserver2.conf
-rw-r--r-- 1 root root 123 4月  19 19:09 testserver3.conf

//内容如下
[root@Nginx conf.d]# cat testserver{1..3}.confserver {        listen 80;
        server_name testserver1 192.168.69.113;

        location / {
                root /soft/code1;                index index.html;
        }
}
server {        listen 80;
        server_name testserver2 192.168.69.113;

        location / {
                root /soft/code2;                index index.html;
        }
}
server {        listen 80;
        server_name testserver3 192.168.69.113;

        location / {
                root /soft/code3;                index index.html;
        }
}

//检测语法
[root@Nginx conf.d]# nginx -tnginx: [warn] conflicting server name "192.168.69.113" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "192.168.69.113" on 0.0.0.0:80, ignored
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

//重启Nginx
[root@Nginx conf.d]# nginx -t

3.测试访问效果

[root@Nginx conf.d]# curl 192.168.69.113<h1>Code 1</h1>
[root@Nginx conf.d]# mv testserver1.conf testserver5.conf[root@Nginx conf.d]# nginx -s reload[root@Nginx conf.d]# curl 192.168.69.113<h1>Code 2</h1>

3.Nginx Include 包含文件

一台服务器配置多个server网站,会导致nginx.conf主配置文件变得非常庞大而且可读性非常的差。

4.Nginx alias 与 root 路径匹配

root路径配置

[root@Nginx ~]# mkdir /local_path/code/request_path/code/ -p[root@Nginx ~]# echo "Root" > /local_path/code/request_path/code/index.html//Nginx的root配置
[root@Nginx ~]# cat /etc/nginx/conf.d/root.conf server {        listen 80;        index index.html;
        location /request_path/code/ {
                root /local_path/code/;
        }
}

//请求测试
[root@Nginx conf.d]# curl http://192.168.69.113/request_path/code/index.htmlRoot

//实际请求本地文件路径为
/local_path/code/'request_path/code'/index.html

alias路径配置

[root@Nginx ~]# mkdir /local_path/code/request_path/code/ -p[root@Nginx ~]# echo "Alias" > /local_path/code/index.html//配置文件
[root@Nginx ~]# cat /etc/nginx/conf.d/alias.conf server {
        listen 80;
        index index.html;
        location /request_path/code/ {
                alias /local_path/code/;
        }
}//测试访问
[root@Nginx ~]# curl http://192.168.69.113/request_path/code/index.htmlAlias//实际访问本地路径/local_path/code/'index.html'

7.Nginx Location

使用Nginx Location控制访问网站规则

一个server可以有多个location配置,但多个location配置的优先级又该如何划分

Location语法规则:

location [=|^~|~|~*|!~|!~*|/] /uri/ { ...
}# Location优先级如[]号显示
完整匹配优先级高
/表示通用匹配,任何请求都会匹配到
=表示精确匹配,优先级最高
^~表示uri以某个常规字符串开头,理解为匹配url路径即可
正则匹配匹配后会继续查找更精确匹配的location
~表示区分大小写的正则匹配
~*表示不区分大小写的正则匹配
非正则匹配
!~表示区分大小写不匹配的正则
!~*表示不区分大小写不匹配的正则

1.实例准备

[root@Nginx conf.d]# cat testserver.conf server {
listen 80;
server_name bgx.com;

  location / {    return 200 "location /";
  }

  location =/ {    return 200 "location =/";
  }

  location ~ / {    return 200 "location ~/";
  } # location ^~ / {
 #  return 200 "location ^~";
 # }}

2.测试效果

[root@Nginx conf.d]# curl bgx.comlocation =///注释掉精确匹配=, 重启Nginx
[root@Nginx ~]# curl bgx.comlocation ~///注释掉~, 重启Nginx
[root@Nginx ~]# curl bgx.comlocation /

8.Nginx Try_file

Nginx try_files路径匹配

nginxtry_files按顺序检查文件是否存在

location /{try_files $uri $uri/ /index.php;
}#1.检查用户请求的uri内容是否存在本地,存在则解析#2.将请求加/, 类似于重定向处理 #3.最后交给index.php处理

1.演示环境准备

[root@Nginx ~]# echo "Try-Page" > /soft/code/index.html[root@Nginx ~]# echo "Tomcat-Page" > /soft/app/apache-tomcat-9.0.7/webapps/ROOT/index.html//启动tomcat
[root@Nginx ~]# sh /soft/app/apache-tomcat-9.0.7/bin/startup.sh//检查tomcat端口
[root@Nginx ~]# netstat -lntp|grep 8080tcp6       0      0 :::8080                 :::*                    LISTEN      104952/java

2.配置Nginxtryfiles

[root@Nginx ~]# cat /etc/nginx/conf.d/try.conf server {        listen 80;
        server_name 192.168.69.113;
        root /soft/code;        index index.html;
        location / {
                try_files $uri @java_page;
        }
        location @java_page {
                proxy_pass http://127.0.0.1:8080;
        }
}

//重启Nginx
[root@Nginx ~]# nginx -s reload

3.测试tryfiles

[root@Nginx ~]# curl http://192.168.69.113/index.htmlTry-Page//将/soft/code/index.html文件移走[root@Nginx ~]# mv /soft/code/{index.html,index.html_bak}//发现由Tomcat吐回了请求[root@Nginx ~]# curl http://192.168.69.113/index.html    Tomcat-Page


本文 暂无 评论

Top