Centos7学习笔记(十八)- nginx基础与模块

一、安装

安装分为2种,yum安装和源码包编译安装。

yum又分为官方源安装和epel源安装。

官方的参考官方文档,主要执行以下3步:

sudo yum install yum-utils
sudo vi /etc/yum.repo.d/nginx.repo
[nginx-stable]

name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/

sudo yum install nginx

编译安装网上很多文章,主要是解决依赖以及模块的定制。

依赖方面,主要有gcc、gcc-c++、make、automake、autoconf、pcre、pcre-devel、zlip、zlib-devel、openssl、openssl-devel 、libtool这些。

其他模块方面根据实际需要编译进去,核心重要的可以参考yum安装默认附加的模块。

--prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-compat --with-debug --with-file-aio --with-google_perftools_module --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_degradation_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_mp4_module --with-http_perl_module=dynamic --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_xslt_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-stream_ssl_preread_module --with-threads --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'


二、nginx配置文件

nginx配置文件分3大区块,每区块都由{}包围。

CoreModule(核心模块)、EventModule(事件驱动模块)、httpCoreModule(http内核模块)


# For more information on configuration, see:

   * Official English Documentation: http://nginx.org/en/docs/

   * Official Russian Documentation: http://nginx.org/ru/dos/

《《=============核心模块===========》》
user nginx;                               《===========nginx主进程用户
worker_processes auto;                     《============工作进程数量,可设置为跟cpu核心数相等,比如8、16
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

 Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.

include /usr/share/nginx/modules/*.conf;          
《《=============事件驱动模块===========》》
events {
    worker_connections 1024;                       《=============每工作进程最大连接数
    use epool;                                      《=============使用epool网络模型,可不写这一行
}

《《=============http内核模块===========》》
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';    《=====日志格式定义,将后面的一堆变量定义的格式存储在main中
    access_log  /var/log/nginx/access.log  main;                 《============定义access.log以main的格式存储
    sendfile            on;                       《=======一种高效的文件传输方式。普通应用可以写on,但对高IO的下载类应用,写off,以平衡磁盘与网络IO处理速度,降低系统uptime。
    tcp_nopush          on;                   《==============此选项允许或禁止使用socke的TCP_CORK的选项,此选项仅在使用sendfile的时候使用
    tcp_nodelay         on;
    keepalive_timeout   65;              《=============长连接的超时时间
    types_hash_max_size 4096;
    include             /etc/nginx/mime.types;                 《===========包括的资源类型文件
    default_type        application/octet-stream;    《===========默认资源类型,指的是如果请求的资源类型,不包括在上面的mime.type类型描述内,定义为的类型,最终是让浏览器以下载的方式获得(响应请求)
    #gzip                    on;                    《==========是否开启页面编码的压缩功能
    
    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include ;
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        error_page 404 /404.html;
        location = /404.html {
        }
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

 Settings for a TLS enabled server.

    server {

        listen       443 ssl http2;

        listen       [::]:443 ssl http2;

        server_name  _;

        root         /usr/share/nginx/html;

        ssl_certificate "/etc/pki/nginx/server.crt";

        ssl_certificate_key "/etc/pki/nginx/private/server.key";

        ssl_session_cache shared:SSL:1m;

        ssl_session_timeout  10m;

        ssl_ciphers HIGH:!aNULL:!MD5;

        ssl_prefer_server_ciphers on;

        # Load configuration files for the default server block.

        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;

            location = /40x.html {

        }

        error_page 500 502 503 504 /50x.html;

            location = /50x.html {

        }

    }

}


三、虚拟主机配置

有三种方式配置虚拟主机:

1、基于多IP的虚拟主机    ——  247.23.225.10:80         247.23.225.11:80             247.23.225.12:80 

2、基于端口的虚拟主机     ——     247.23.225.10:80      247.23.225.10:81           247.23.225.10:82

3、基于多域名的虚拟主机        ——      ww.test123.com       www.test234.com           www.test345.com

nignx配置文件自查测试

ningx -t和systemctl status ningx -l


四、nginx日志

1、配置文件中,用log_format(等同于一个命令)来定义日志语法格式。定义的格式用于access.log和error.log。

log_format自身的语法为:

log_format  name   [escape=default|json]                 string  - - -;
说明:log_format指令   变量名(有个定义好的main,可自行再定义)   日志封装记录格式,可以是json格式   日志变量字符串,一般都用其允许的变量联合

log_format的定义,必须是在“http内核模块”内,其他的不生效。

log_format日志的默认联合符号是“-”


日志格式允许的变量

$remote_addr&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#记录客户端的IP地址</p><p style="text-align: left;">$remote_user                        #记录客户端用户名

$time_iso8601&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#记录ISO8601标准格式下的本地时间<br style="text-align: left;"/></p><p style="text-align: left;">$request                                #记录请求的方法以及请求的http协议

$status&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#记录请求的状态码(用于定位错误信息)</p><p style="text-align: left;">$body_bytes_sent                    #发送给客户端的资源字节数,不包括响应头的大小

$bytes_sent&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#发送给客户端的总字节数<br style="text-align: left;"/></p><p style="text-align: left;">$msec                                    #日志写入时间。单位为秒,精度为毫秒

$http_referer&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#记录从哪个页面链接访问过来的<br style="text-align: left;"/></p><p style="text-align: left;">$http_user_agent                    #记录客户端浏览器相关信息

$http_x_forward_for&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#记录客户端IP<br style="text-align: left;"/></p><p style="text-align: left;">$request_length                        #请求的长度(包括请求行,请求头和请求正文)

$request_time&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #请求的时间,单位为秒,精度为毫秒</p><p style="text-align: left;">$time_local                              #访问时间和时区                                18/Jul/2012:17:00:01 +0800

$http_host&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#请求地址,即浏览器中你输入的地址(IP或域名)&nbsp; &nbsp; &nbsp;www.wang.com 192.168.100.100</p><p style="text-align: left;">$upstream_status                     #upstream状态                                  200

$ssl_protocol&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#SSL协议版本&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TLSv1</p><p style="text-align: left;">$ssl_cipher                                 # 交换数据中的算法                               RC4-SHA

$upstream_addr&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; #后台upstream的地址,即真正提供服务的主机地址&nbsp; &nbsp; &nbsp;10.10.10.100:80</p><p style="text-align: left;">$upstream_response_time          #请求过程中,upstream响应时间                    0.002


2、access_log日志配置语法
access_log   path  [format [buffer=size]  [gzip=[level]]   [flush=time]  [if=condition] ];

也可以

access_log   off;

默认用法:

access_log        logs/access.log              combined;

access_log匹配使用在http、server、location、if in location、limit_except几个模块内

access_log如果定义在server模块内,那么就仅记录该网站的日志,全局的,访问其他网站的日志,记录在http模块定义的access_log中。

location模块一般定义access_log off


3、error_log作用域是main, http, server, location。它有几个定义好的日志层级:debug | info | notice | warn | error | crit | alert | emerg

error_log定义方法:

error_log            FILE                        level

error_log       /var/log/nginx/error.log        warn;

注意:不要配置info等级较低的级别,会带来大量的磁盘I/O消耗

其实,error_log定义在main和http中,是有点区别的,有兴趣可以看看https://blog.csdn.net/fangru/article/details/9128699  这篇文章。但一般不用过多理会。


五、nginx常用模块

1、nginx目录索引模块

ngx_http_autoindex_module模块处理以斜杠字符('/')为结尾的请求,并生成目录列表。当ngx_http_index_module模块找不到索引文件时,通常会将请求传递给模块。

a、指令

autoinex   on|off ;


示例配置文件:

server{
        listen    80;
        server_name        index.test.com;
        
        location    /    {
                root        /index;
                autoindex    on;
        }
}

bash下:

mkdir -p /index/testdir{1..20}

b、其他问题

charset     utf-8,gbk;          《===========写在server段,用于控制网站输出的字符集,解决乱码问题
autoindex_exact_size   on|off;   《=============作用域:http模块、server模块、location模块。用于输出index索引出的文件大小,off表示用大概的“K、M“”输出显示,on表示用确切的字节值显示。默认是on。
autoindex_localtime  on|off;   《========作用域:http模块、server模块、location模块。写在location段,用于指定目录列表中的时间是本地时区还是UTC输出,on本地时区,off表示UTC时区,默认是off。

2、nginx状态监控模块

ngx_http_stub_status_module模块用于提供基本的状态信息。在编译安装时,它默认不编译进去,需要用--with-http_stub_status_module参数才能编译进去。

示例:

location = /basic_status {
    stub_status;
}

a、指令
stub_status;

默认没有值。作用域:server、location。

b、状态页面输出信息解读

Active connections                        《==============    当前活动客户端连接数,包括wating等待的连接数。

accepts                                           《=============已接受的总的tcp连接数

handled                                           《============已处理的总的TCP连接数

request                                            《============客户端总的http请求数


Reading                                            《===========当前nginx读取请求头的连接数

Writing                                              《=============当前nginx将响应写回客户端的连接数

Waiting                                               《==========当前等待请求的空闲客户端连接数

注意,一次TCP连接,可产生多次http请求,可配置如下参数进行验证:

keepalive_timeout        0;                            《==============类似于关闭长连接;

3、nignx访问控制模块

ngx_http_access_module模块允许限制对某些客户端地址的访问。

a、指令

允许的语法配置:

allow        address|CIDR|unix:|all;                          《============常用的是address和all,address是基于IP地址

拒绝的语法配置:

deny        address|CIDR|unix:|all;

allow和deny的作用域都是http、server、location、limit_except。

示例:

location /nginx_status {
    stub_status;
    allow 10.0.0.0/24;
    deny all;
}

允许使用Http基本身份验证,验证用户名和密码来限制对资源的访问。
a、指令
auth_basic       |off;            《============是描述性字符串,默认的是auth_basic  off。
指令作用域:http, server, location, limit_except
auth_basic_user_file    ;                              《==============为指定的认证用文件
指令作用域:http, server, location, limit_except
示例文件:
location / {
    auth_basic           "closed site";                    《=============引号内内容为描述性字符串
    auth_basic_user_file conf/htpasswd;                    《=============文件可以写绝对路径,也可以写相对路径,相对路径指相对/etg/nginx目录。 
}

其中,上述示例中,htpasswd文件内容格式应该如下:

# comment
name1:password1
name2:password2:comment
name3:password3

常规的,用htpasswd命令来生成这个文件,该命令,存在于httpd-tools软件包中,如果没有,需安装。

htpasswd命令用法:

[study@web01 ~]$htpasswd 
Usage:
htpasswd [-cimB25dpsDv] [-C cost] [-r rounds] passwordfile username
htpasswd -b[cmB25dpsDv] [-C cost] [-r rounds] passwordfile username password
htpasswd -n[imB25dps] [-C cost] [-r rounds] username
htpasswd -nb[mB25dps] [-C cost] [-r rounds] username password
 -c  Create a new file.
 -n  Don't update file; display results on stdout.
 -b  Use the password from the command line rather than prompting for it.
 -i  Read password from stdin without verification (for script usage).
 -m  Force MD5 encryption of the password (default).
 -2  Force SHA-256 crypt() hash of the password (secure).
 -5  Force SHA-512 crypt() hash of the password (secure).
 -B  Force bcrypt aencryption of the password (very secure).
 -C  Set the computing time used for the bcrypt algorithm
     (higher is more secure but slower, default: 5, valid: 4 to 31).
 -r  Set the number of rounds used for the SHA-256, SHA-512 algorithms
     (higher is more secure but slower, default: 5000).
 -d  Force CRYPT encryption of the password (8 chars max, insecure).
 -s  Force SHA-1 encryption of the password (insecure).
 -p  Do not encrypt the password (plaintext, insecure).
 -D  Delete the specified user.
 -v  Verify password for the specified user.

示例:htpasswd -c -b /etc/nginx/auth_conf   authuser   authpasswd


4、nginx访问限制模块

实际上,这里有2个模块,ngx_http_limit_conn_module模块和ngx_http_limit_req_module。

A、

ngx_http_limit_conn_module模块解释:设置共享内存区域和给定键值的最大允许连接数。超过此限制时,服务器将返回错误回复请求(默认503,可指定错误状态码)

具体使用上,涉及2个指令,limit_conn_zone需要指定在http模块内。limit_conn指令作用在http、server、location模块内。

示例配置文件:

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    ...

    server {

        ...

        location /download/ {
            limit_conn addr 1;
        }

上述示例中,

a)    $binary_remote_addr变量表示IP地址,也可以是其他变量,比如$server_name(引入$server_name的话,那么限制就是针对该主机总的连接数)。具体用什么变量,取决于你想limit的维度。与$binary_remote_addr类似的有一个$remote_addr变量,二者的区别,是后者长度是7到15字节,而前者是固定的4字节。对应同大小的内存区域空间来说,明显前者能存储更多。<br style="text-align: left;"/></p><p style="text-align: left;">b)&nbsp;&nbsp;&nbsp;&nbsp;zone定义的是区域的名称,具体名称可以随意起,主要是后面limit_conn指令需要引用该名称。</p><p style="text-align: left;">c)&nbsp;&nbsp;&nbsp;&nbsp;limit_conn指令的具体写法就是“limit_conn&nbsp;&nbsp;&nbsp;&nbsp;区域名称&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;想限制的数值”。</p><p style="text-align: left;">另一个配置实例:<br style="text-align: left;"/></p><pre style="box-sizing: border-box; font-size: 12px; font-family: Consolas, Monaco, &quot;Andale Mono&quot;, &quot;Ubuntu Mono&quot;, monospace; margin-top: 0px; margin-bottom: 20px; overflow: scroll auto; overflow-wrap: normal; word-break: break-all; overscroll-behavior-x: contain; border-radius: 4px; z-index: 0; padding: 1em 1em 1em 3.8em; line-height: 1.5; color: rgb(204, 204, 204); background-color: rgb(45, 45, 45); tab-size: 4; hyphens: none; position: relative; counter-reset: linenumber 0;">&nbsp;&nbsp;&nbsp;&nbsp;limit_conn_zone&nbsp;$binary_remote_addr zone=perip:10m; 
    limit_conn_zone $server_name  zone=perserver:20m; 
    limit_conn_log_level info; 
    limit_conn_status 503;
    
    server {
    listen       8000;
    server_name  localhost;
        limit_conn perserver 3; 
        
        location /limit {
           limit_conn perip 2; 
           #  add_header Content-Type "text/plain;charset=utf-8";
           #  return 200 "Your IP:$remote_addr";
           proxy_pass http://127.0.0.1:8081
        }
    }

B、

ngx_http_limit_req_module模块

用于限制共享区域内http请求的速率,包括指定最大突发大小。超过请求速率的过多请求被延迟,直到它们的数量超过最大突发大小,在这种情况下请求以错误终止。默认情况下,最大突发大小为零。

同样涉及2个指令,limit_req_zonelimit_req。前者写在http模块内,后者作用域http, server, location。

limit__req指令的语法:

Syntax:limit_req zone=name [burst=number] [nodelay | delay=number];       《===========nodelay在超过设定的请求速率,达到burst时,多余的访问请求直接被拒绝,不延迟
Default:

两个指令结合使用,典型的配置文件如下:

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    ...

    server {

        ...

        location /search/ {
            limit_req zone=one burst=5;
        }

另外的典型配置如下:

limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;
limit_req_zone $server_name zone=perserver:10m rate=10r/s;

server {
    ...
    limit_req zone=perip burst=5 nodelay;
    limit_req zone=perserver burst=10;
    limit_req_status 412;
}


六、location模块定义

1、location语法示例

location  [ = | ^~ | ~ | ~ | !~ | !~ | /]  /uri/  {....

}

2、location语法优先级排列

匹配符
匹配规则
优先级
=精确匹配1
^~以某个字符串开头2
~
区分大小写的正则匹配
3
~
不区分大小写的正则匹配4
!~
区分大小写不匹配的正则
5
!~不区分大小写不匹配的正则
6
/
通用匹配,任何请求都会被匹配到
7


七、favicon.ico请求的处理

一种常见的方式是:

        location /favicon.ico {

                return 200;

                access_log    off;

        }

2021 10月 07