Nginx

Nginx(1)

简介:Nginx(一)

1. Nginx的基础

1.1. 环境调试确认

  1. yum源修改
  • 下载repo文件
  • [root@localhost ~]# wget http://mirrors.aliyun.com/repo/Centos-7.repo
  • 备份并替换系统的repo文件
  • [root@localhost ~]# cp Centos-7.repo /etc/yum.repos.d/
  • [root@localhost ~]# cd /etc/yum.repos.d/
  • [root@localhost yum.repos.d]# mv CentOS-Base.repo CentOS-Base.repo.bak
  • [root@localhost yum.repos.d]# mv Centos-7.repo CentOS-Base.repo
  • 执行yum源更新命令
  • [root@localhost yum.repos.d]# yum clean all
  • [root@localhost yum.repos.d]# yum makecache
  • [root@localhost yum.repos.d]# yum update
  1. 两项安装
  • [root@localhost ~]# yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake
  • Loaded plugins: fastestmirror
  • Loading mirror speeds from cached hostfile
  • * base: mirrors.aliyun.com
  • * extras: mirrors.aliyun.com
  • * updates: mirrors.aliyun.com
  • Package gcc-4.8.5-16.el7_4.1.x86_64 already installed and latest version
  • Package gcc-c++-4.8.5-16.el7_4.1.x86_64 already installed and latest version
  • Package autoconf-2.69-11.el7.noarch already installed and latest version
  • Package pcre-8.32-17.el7.x86_64 already installed and latest version
  • Package pcre-devel-8.32-17.el7.x86_64 already installed and latest version
  • Package 1:make-3.82-23.el7.x86_64 already installed and latest version
  • Package automake-1.13.4-3.el7.noarch already installed and latest version
  • Nothing to do
  • [root@localhost ~]# yum -y install wget httpd-tools vim
  • Loaded plugins: fastestmirror
  • Loading mirror speeds from cached hostfile
  • * base: mirrors.aliyun.com
  • * extras: mirrors.aliyun.com
  • * updates: mirrors.aliyun.com
  • Package wget-1.14-15.el7_4.1.x86_64 already installed and latest version
  • Package httpd-tools-2.4.6-67.el7.centos.6.x86_64 already installed and latest version
  • Package 2:vim-enhanced-7.4.160-2.el7.x86_64 already installed and latest version
  • Nothing to do
  1. 初始化目录
  • [root@localhost ~]# cd /opt;mkdir app download logs work backup
  • [root@localhost opt]# ls
  • app backup download logs work
  1. 关闭iptables
  • [root@localhost ~]# iptables -F
  • [root@localhost ~]# iptables -t nat -F
  1. 关闭SELinux
  • [root@localhost ~]# getenforce
  • Enforcing
  • [root@localhost ~]# setenforce 0
  • [root@localhost ~]# getenforce
  • Permissive

1.2. 安装Nginx

我们可以在yum源的目录下创建一个ngnix.repo的文件,内容如下:

  • [nginx]
  • name=nginx repo
  • baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
  • gpgcheck=0
  • enabled=1

然后直接使用yum进行安装:

  • [root@localhost yum.repos.d]# yum install nginx

可以通过-v-V查看Nginx的版本信息:

  • [root@localhost yum.repos.d]# nginx -v
  • nginx version: nginx/1.13.8
  • [root@localhost yum.repos.d]# nginx -V
  • nginx version: nginx/1.13.8
  • built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
  • built with OpenSSL 1.0.2k-fips 26 Jan 2017
  • TLS SNI support enabled
  • configure arguments: --prefix=/etc/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 --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --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-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

1.3. Nginx安装目录讲解

使用rpm -ql nginx查看Nginx安装的目录和内容:

  • [root@localhost ~]# rpm -ql nginx
  • /etc/logrotate.d/nginx
  • /etc/nginx
  • /etc/nginx/conf.d
  • /etc/nginx/conf.d/default.conf
  • /etc/nginx/fastcgi_params
  • /etc/nginx/koi-utf
  • /etc/nginx/koi-win
  • /etc/nginx/mime.types
  • /etc/nginx/modules
  • /etc/nginx/nginx.conf
  • /etc/nginx/scgi_params
  • /etc/nginx/uwsgi_params
  • /etc/nginx/win-utf
  • /etc/sysconfig/nginx
  • /etc/sysconfig/nginx-debug
  • /usr/lib/systemd/system/nginx-debug.service
  • /usr/lib/systemd/system/nginx.service
  • /usr/lib64/nginx
  • /usr/lib64/nginx/modules
  • /usr/libexec/initscripts/legacy-actions/nginx
  • /usr/libexec/initscripts/legacy-actions/nginx/check-reload
  • /usr/libexec/initscripts/legacy-actions/nginx/upgrade
  • /usr/sbin/nginx
  • /usr/sbin/nginx-debug
  • /usr/share/doc/nginx-1.13.8
  • /usr/share/doc/nginx-1.13.8/COPYRIGHT
  • /usr/share/man/man8/nginx.8.gz
  • /usr/share/nginx
  • /usr/share/nginx/html
  • /usr/share/nginx/html/50x.html
  • /usr/share/nginx/html/index.html
  • /var/cache/nginx
  • /var/log/nginx

各类重要文件的作用如下:

路径 类型 作用
/etc/logrotate.d/nginx 配置文件 Nginx日志轮转,用于logrotate服务的日志切割
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/nginx.conf
/etc/nginx/conf.d/default.conf
目录,配置文件 Nginx主配置文件
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/fastcgi_params
配置文件 cgi配置相关,fastcgi配置
/etc/nginx/mime.types 配置文件 设置http协议的Content-Type与扩展名的对应关系
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
配置文件 用于配置系统守护进程管理器管理方式
/usr/lib64/nginx/modules
/etc/nginx/modules
目录 Nginx模块目录
/usr/sbin/nginx
/usr/sbin/nginx-debug
命令 Nginx服务的启动管理的终端命令
/usr/share/doc/nginx-1.13.8
/usr/share/doc/nginx-1.13.8/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
文件、目录 Nginx的手册和帮助文件
/var/cache/nginx 目录 Nginx的缓存目录
/var/log/nginx 目录 Nginx的日志目录

1.4. Nginx安装编译参数

  1. 安装目的目录或路径
  • --prefix=/etc/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
  • --pid-path=/var/run/nginx.pid
  • --lock-path=/var/run/nginx.lock
  1. 执行对应模块时,Nginx所保留的临时性文件
  • --http-client-body-temp-path=/var/cache/nginx/client_temp
  • --http-proxy-temp-path=/var/cache/nginx/proxy_temp
  • --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
  • --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
  • --http-scgi-temp-path=/var/cache/nginx/scgi_temp
  1. 设定Nginx进行启动的用户和组用户
  • --user=nginx
  • --group=nginx
  1. 设置额外的参数将被添加到CFLAGS变量
  • --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC'
  1. 设置附加的参数,链接系统库
  • --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

2. HTTP请求

  • [root@localhost ~]# curl -v https://www.baidu.com >/dev/null
  • % Total % Received % Xferd Average Speed Time Time Time Current
  • Dload Upload Total Spent Left Speed
  • 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* About to connect() to www.baidu.com port 443 (#0)
  • * Trying 115.239.211.112...
  • * Connected to www.baidu.com (115.239.211.112) port 443 (#0)
  • * Initializing NSS with certpath: sql:/etc/pki/nssdb
  • * CAfile: /etc/pki/tls/certs/ca-bundle.crt
  • CApath: none
  • * SSL connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  • * Server certificate:
  • * subject: CN=baidu.com,OU=service operation department.,O="BeiJing Baidu Netcom Science Technology Co., Ltd",L=beijing,ST=beijing,C=CN
  • * start date: Jun 29 00:00:00 2017 GMT
  • * expire date: Aug 17 23:59:59 2018 GMT
  • * common name: baidu.com
  • * issuer: CN=Symantec Class 3 Secure Server CA - G4,OU=Symantec Trust Network,O=Symantec Corporation,C=US
  • > GET / HTTP/1.1
  • > User-Agent: curl/7.29.0
  • > Host: www.baidu.com
  • > Accept: */*
  • >
  • < HTTP/1.1 200 OK
  • < Accept-Ranges: bytes
  • < Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
  • < Connection: Keep-Alive
  • < Content-Length: 2443
  • < Content-Type: text/html
  • < Date: Thu, 01 Feb 2018 16:26:49 GMT
  • < Etag: "58860429-98b"
  • < Last-Modified: Mon, 23 Jan 2017 13:24:57 GMT
  • < Pragma: no-cache
  • < Server: bfe/1.0.8.18
  • < Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
  • <
  • { [data not shown]
  • 100 2443 100 2443 0 0 21716 0 --:--:-- --:--:-- --:--:-- 21812
  • * Connection #0 to host www.baidu.com left intact

3. Nginx的配置文件讲解

  1. /etc/nginx/nginx.conf文件

该文件内容如下:

  • user nginx;
  • worker_processes 1;
  • error_log /var/log/nginx/error.log warn; # 错误日志位置以及级别
  • pid /var/run/nginx.pid;
  • events {
  • worker_connections 1024;
  • }
  • http {
  • include /etc/nginx/mime.types;
  • default_type application/octet-stream;
  • 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; # 访问日志,使用上面配置的main格式化工具
  • sendfile on;
  • #tcp_nopush on;
  • keepalive_timeout 65;
  • #gzip on;
  • include /etc/nginx/conf.d/*.conf;
  • }

在上面配置文件中,对格式化工具的配置有一些Nginx变量需要注意:

  • HTTP请求变量:
  • arg_PARAMETER:请求参数,以$arg_参数名的方式进行输出
  • http_HEADER:请求头信息,以$http_头信息名的方式进行输出
  • sent_http_HEADER:响应头信息,以$sent_http_头信息名的方式进行输出

我们可以修改/etc/nginx/nginx.conf文件添加一些特殊的变量:

  • ...
  • log_format main '$http_user_agent' '$remote_addr - $remote_user [$time_local] "$request" '
  • '$status $body_bytes_sent "$http_referer" '
  • '"$http_user_agent" "$http_x_forwarded_for"';
  • ...

在上面的文件中,我们添加了$http_user_agent变量用于记录用户访问Agent,然后使用nginx -t -c /etc/nginx/nginx.conf文件来检查配置是否正确,然后使用nginx -s reload -c /etc/nginx/nginx.conf来刷新配置:

  • [root@localhost ~]# nginx -t -c /etc/nginx/nginx.conf
  • nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  • nginx: configuration file /etc/nginx/nginx.conf test is successful
  • [root@localhost ~]# nginx -s reload -c /etc/nginx/nginx.conf
  • nginx: [error] invalid PID number "" in "/var/run/nginx.pid"
  • [root@localhost ~]# ps -ef | grep nginx
  • root 2481 1 0 06:29 ? 00:00:00 sshd: nginx [priv]
  • nginx 2485 2481 0 06:29 ? 00:00:02 sshd: nginx@pts/0
  • nginx 2486 2485 0 06:29 pts/0 00:00:00 -bash
  • root 43870 3474 0 08:47 pts/0 00:00:00 grep --color=auto nginx
  • [root@localhost ~]# echo 2481 > /var/run/nginx.pid
  • [root@localhost ~]# nginx -s reload -c /etc/nginx/nginx.conf

注:如果出现nginx: [error] invalid PID number "" in "/var/run/nginx.pid"错误,可以按上面的方式解决。

配置后好,我们使用curl命令请求本机,并且查看访问日志:

  • [root@localhost ~]# curl http://127.0.0.1
  • [root@localhost ~]# curl http://127.0.0.1
  • [root@localhost ~]# tail /var/log/nginx/access.log
  • Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36192.168.127.1 - - [01/Feb/2018:08:50:24 -0800] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-"
  • Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36192.168.127.1 - - [01/Feb/2018:08:50:24 -0800] "GET /favicon.ico HTTP/1.1" 404 571 "http://192.168.127.140/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-"
  • Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36192.168.127.1 - - [01/Feb/2018:08:50:29 -0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-"
  • Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36192.168.127.1 - - [01/Feb/2018:08:50:29 -0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-"
  • Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36192.168.127.1 - - [01/Feb/2018:08:50:29 -0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-"
  • curl/7.29.0127.0.0.1 - - [01/Feb/2018:08:51:24 -0800] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
  • curl/7.29.0127.0.0.1 - - [01/Feb/2018:08:51:27 -0800] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

可以发现每行日志开头都新增了一些User-Agent信息。

/etc/nginx/nginx.conf文件最后一行include /etc/nginx/conf.d/*.conf;表示还引入了这个文件,我们可以看看这个文件的内容。

  1. /etc/nginx/conf.d/default.conf
  • server {
  • listen 80; # server监听的端口
  • server_name localhost; # 服务名,可以是域名地址
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • location / { # 默认的访问位置
  • root /usr/share/nginx/html; # 访问路径
  • index index.html index.htm; # 访问的文件
  • }
  • #error_page 404 /404.html;
  • # redirect server error pages to the static page /50x.html
  • #
  • error_page 500 502 503 504 /50x.html; # 错误页面,可以在这里添加404等错误页面
  • location = /50x.html {
  • root /usr/share/nginx/html;
  • }
  • # proxy the PHP scripts to Apache listening on 127.0.0.1:80
  • #
  • #location ~ \.php$ {
  • # proxy_pass http://127.0.0.1;
  • #}
  • # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  • #
  • #location ~ \.php$ {
  • # root html;
  • # fastcgi_pass 127.0.0.1:9000;
  • # fastcgi_index index.php;
  • # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  • # include fastcgi_params;
  • #}
  • # deny access to .htaccess files, if Apache's document root
  • # concurs with nginx's one
  • #
  • #location ~ /\.ht {
  • # deny all;
  • #}
  • }

注:systemctl restart nginx.service可以重启Nginx服务,systemctl reload nginx.service可以软重启。

4. Nginx模块讲解

可以使用nginx -V查看安装的模块:

  • [root@localhost ~]# nginx -V
  • nginx version: nginx/1.13.8
  • built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
  • built with OpenSSL 1.0.2k-fips 26 Jan 2017
  • TLS SNI support enabled
  • configure arguments: --prefix=/etc/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 --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --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-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

其中:

  • --with-compat
  • --with-file-aio
  • --with-threads
  • --with-http_addition_module
  • --with-http_auth_request_module
  • --with-http_dav_module
  • --with-http_flv_module
  • --with-http_gunzip_module
  • --with-http_gzip_static_module
  • --with-http_mp4_module
  • --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-mail
  • --with-mail_ssl_module
  • --with-stream
  • --with-stream_realip_module
  • --with-stream_ssl_module
  • --with-stream_ssl_preread_module

即是所有安装了的模块名。下面我们将一一讲解。

4.1. --with-http_stub_status_module模块

  1. http_stub_status_module的配置语法

该模块主要用于展示Nginx当前的客户端状态,用于监控Nginx当前连接的信息。它的配置语法、默认配置和配置的上下文如下:

  • Syntax: stub_status;
  • Default: --
  • Context: server,location

我们现在来配置这个模块。在/etc/nginx/conf.d/default.conf中添加以下信息:

  • server {
  • listen 80;
  • server_name localhost;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • location /mystatus {
  • stub_status;
  • }
  • location / {
  • root /usr/share/nginx/html;
  • index index.html index.htm;
  • }
  • ...

然后使用nginx -tc检查配置文件并使用nginx -s reload -c来Reload配置文件:

  • [root@localhost ~]# nginx -tc /etc/nginx/nginx.conf
  • nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  • nginx: configuration file /etc/nginx/nginx.conf test is successful
  • [root@localhost ~]# nginx -s reload -c /etc/nginx/nginx.conf

然后我们在浏览器中访问Nginx所在服务器的IP和路径,例如http://192.168.127.140/mystatus,浏览器会显示以下信息:

  • Active connections: 1
  • server accepts handled requests
  • 2 2 3
  • Reading: 0 Writing: 1 Waiting: 0

返回各数据项说明树下:

  • Active connections:当前nginx正在处理的活动连接数.
  • Server accepts handled requests request_time:Nginx总共处理了2个连接,成功创建2次握手(证明中间没有失败的)总共处理了3个请求。
  • Reading:Nginx读取到客户端的Header信息数.
  • Writing:Nginx返回给客户端的Header信息数.
  • Waiting:开启keep-alive的情况下,这个值等于active-(reading + writing),意思就是Nginx已经处理完成,正在等候下一次请求指令的驻留连接。

在访问效率高,请求很快被处理完毕的情况下,Waiting数比较多是正常的;如果reading +writing数较多,则说明并发访问量非常大,正在处理过程中。

4.2. --with-http_random_index_module模块

该模块用于在Nginx主目录中随机选择一个文件作为访问时展示的主页。它的配置语法、默认配置和配置的上下文如下:

  • Syntax: random_index on | off;
  • Default: random_index off;
  • Context: location

我们现在来配置这个模块。在/etc/nginx/conf.d/default.conf中配置以下信息:

  • server {
  • listen 80;
  • server_name localhost;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • # 可以显示nginx的状态
  • location /mystatus {
  • stub_status;
  • }
  • # 可以随机展示主页
  • location / {
  • root /opt/app/code;
  • random_index on;
  • # index index.html index.htm;
  • }
  • ...

我们将根路径定位到了/opt/app/code中,然后将random_index置为on,在/opt/app/code目录下有三个HTML文件分别展示了三个网页,每个页面上的颜色都不一样。配置完后对配置文件进行检查并且刷新配置文件,然后使用systemctl reload nginx软重启Nginx,访问Nginx所在服务器的主页,可以发现,没刷新一次,页面都会随机改变。

注:需要注意的是,Nginx不会显示隐藏的HTML文件(以.开头的隐藏文件)。

4.3. --with-http_sub_module模块

该模块用于HTTP内容替换。它有多个配置,配置语法、默认配置和配置的上下文如下:

  1. 使用字符串替换:
  • Syntax: sub_filter string replacement;
  • Default: --
  • Context: http, server, location
  1. 用于服务端完成与客户端进行每一次请求的时候校验服务端的内容是否有更新,主要用于缓存中:
  • Syntax: sub_filter_last_modified on | off;
  • Default: sub_filter_last_modified off;
  • Context: server, location
  1. 用于配置在filter的时候是匹配所有HTML代码中的第一个字符串,还是匹配所有字符串:
  • Syntax: sub_filter_once on | off;
  • Default: sub_filter_once on;
  • Context: http, server, location

我们在/opt/app/code/下有一个http_sub_module.html文件,内容如下:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>Http Sub Module</title>
  • </head>
  • <body>
  • <a href="">aaaaa</a>
  • <a href="">bbbbb</a>
  • <a href="">ccccc</a>
  • <a href="">ddddd</a>
  • <a href="">aaaaa</a>
  • <a href="">bbbbb</a>
  • <a href="">ccccc</a>
  • <a href="">ddddd</a>
  • </body>
  • </html>

我们可以是直接请求该页面,内容如下:

1.1.http_sub_module之前的页面内容

然后在/etc/nginx/conf.d/default.conf中配置以下信息:

  • server {
  • listen 80;
  • server_name localhost;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • # 用于替换页面上的某些内容
  • location / {
  • root /opt/app/code/;
  • index index.html index.htm;
  • sub_filter 'aaaaa' 'replaced_aaaaa';
  • }
  • ...

上面的配置中,指定了替换功能,会把每次请求内容中的aaaaa内容替换为replaced_aaaaa。配置完后检查并刷新配置文件,同时软重启Nginx,然后刷新页面查看内容如下:

1.2.http_sub_module之后的页面内容

可以发现,页面中第一个aaaaa已被替换为了replaced_aaaaa,但是仅仅替换了一个,这是由于http_sub_module模块的sub_filter_once配置默认是开启的,我们可以手动将其关闭:

  • ...
  • # 用于替换页面上的某些内容
  • location / {
  • root /opt/app/code/;
  • index index.html index.htm;
  • sub_filter 'aaaaa' 'replaced_aaaaa';
  • sub_filter_once off;
  • }
  • ...

然后对Nginx进行刷新重启,访问页面如下:

1.3.关闭sub_filter_once之后的页面内容

可以发现,此时页面中所有的aaaaa都被替换了。

4.4. Nginx的请求限制

Nginx的请求限制可以通过下面的配置实现:

  • 连接频率限制:-limit_conn_module
  • 请求频率限制:-limit_req_module
  1. 连接限制。对于连接限制,有以下的配置方式:
  • Syntax: limit_conn_zone key zone=name:size;
  • Default: -
  • Context: http

上面的配置项是用于指定限制连接时存储连接信息的内存名称和大小。

  • Syntax: limit_conn zone number;
  • Default: -
  • Context: http, server, location

上面的配置项是用于指定对应zone的最大连接数量。

  1. 请求限制
  • Syntax: limit_req_zone key zone=name:size rate=rate;
  • Default: -
  • Context: http

上面的配置项是用于指定限制请求时存储连接信息的内存名称和大小以及请求速率。

  • Syntax: limit_req zone=name [burst=number] [nodelay];
  • Default: -
  • Context: http, server, location

上面的配置项是用于指定对应zone的某些配置信息。

我们首先直接对没有配置任何限制的Nginx服务器进行压力测试,使用ab命令:

  • [root@centos ~]# ab -n 50 -c 20 http://192.168.127.140/1.html
  • This is ApacheBench, Version 2.3 <$Revision: 655654 $>
  • Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
  • Licensed to The Apache Software Foundation, http://www.apache.org/
  • Benchmarking 192.168.127.140 (be patient).....done
  • Server Software: nginx/1.13.8
  • Server Hostname: 192.168.127.140
  • Server Port: 80
  • Document Path: /1.html
  • Document Length: 158 bytes
  • Concurrency Level: 20
  • Time taken for tests: 0.012 seconds
  • Complete requests: 50
  • Failed requests: 0
  • Write errors: 0
  • Total transferred: 19500 bytes
  • HTML transferred: 7900 bytes
  • Requests per second: 4094.67 [#/sec] (mean)
  • Time per request: 4.884 [ms] (mean)
  • Time per request: 0.244 [ms] (mean, across all concurrent requests)
  • Transfer rate: 1559.49 [Kbytes/sec] received
  • Connection Times (ms)
  • min mean[+/-sd] median max
  • Connect: 0 0 0.3 0 1
  • Processing: 1 3 0.8 3 3
  • Waiting: 0 2 0.8 3 3
  • Total: 1 3 0.6 3 4
  • WARNING: The median and mean for the waiting time are not within a normal deviation
  • These results are probably not that reliable.
  • Percentage of the requests served within a certain time (ms)
  • 50% 3
  • 66% 3
  • 75% 3
  • 80% 3
  • 90% 3
  • 95% 4
  • 98% 4
  • 99% 4
  • 100% 4 (longest request)

注:-n表示总共发起的请求数,-c表示同时并发的请求数。

可以发现,所有的请求都被成功处理了。

然后我们在/etc/nginx/conf.d/default.conf中配置请求限制信息:

  • server {
  • listen 80;
  • server_name localhost;
  • limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • # 用于请求限制
  • location / {
  • root /opt/app/code/;
  • limit_req zone=req_zone;
  • index index.html index.htm;
  • }
  • ...

在上面的配置中limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;指定了请求限制的zone为req_zone,大小为1MB,并且每秒钟对于每个远程地址只响应一次请求。然后再次使用ab命令对该服务器进行压力测试:

  • [root@centos ~]# ab -n 50 -c 20 http://192.168.127.140/1.html
  • This is ApacheBench, Version 2.3 <$Revision: 655654 $>
  • Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
  • Licensed to The Apache Software Foundation, http://www.apache.org/
  • Benchmarking 192.168.127.140 (be patient).....done
  • Server Software: nginx/1.13.8
  • Server Hostname: 192.168.127.140
  • Server Port: 80
  • Document Path: /1.html
  • Document Length: 158 bytes
  • Concurrency Level: 20
  • Time taken for tests: 0.023 seconds
  • Complete requests: 50
  • Failed requests: 49
  • (Connect: 0, Receive: 0, Length: 49, Exceptions: 0)
  • Write errors: 0
  • Non-2xx responses: 49
  • Total transferred: 36209 bytes
  • HTML transferred: 26471 bytes
  • Requests per second: 2147.95 [#/sec] (mean)
  • Time per request: 9.311 [ms] (mean)
  • Time per request: 0.466 [ms] (mean, across all concurrent requests)
  • Transfer rate: 1519.05 [Kbytes/sec] received
  • Connection Times (ms)
  • min mean[+/-sd] median max
  • Connect: 0 0 0.3 0 1
  • Processing: 1 8 7.2 3 18
  • Waiting: 0 8 7.2 3 18
  • Total: 2 9 7.5 3 19
  • Percentage of the requests served within a certain time (ms)
  • 50% 3
  • 66% 17
  • 75% 17
  • 80% 18
  • 90% 18
  • 95% 19
  • 98% 19
  • 99% 19
  • 100% 19 (longest request)

可以发现,这一次的请求由于配置了请求限制,每秒只响应一个地址发送的一次请求,所有有49个请求是失败的:

  • Complete requests: 50
  • Failed requests: 49
  • (Connect: 0, Receive: 0, Length: 49, Exceptions: 0)
  • Write errors: 0
  • Non-2xx responses: 49

我们可以查看Nginx的错误日志:

  • [root@localhost nginx]# tail /var/log/nginx/error.log
  • 2018/02/03 01:33:34 [error] 1664#1664: *116 limiting requests, excess: 0.978 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *117 limiting requests, excess: 0.978 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *118 limiting requests, excess: 0.978 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *119 limiting requests, excess: 0.978 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *120 limiting requests, excess: 0.978 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *121 limiting requests, excess: 0.978 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *122 limiting requests, excess: 0.977 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *123 limiting requests, excess: 0.977 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *124 limiting requests, excess: 0.977 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"
  • 2018/02/03 01:33:34 [error] 1664#1664: *125 limiting requests, excess: 0.977 by zone "req_zone", client: 192.168.127.133, server: localhost, request: "GET /1.html HTTP/1.0", host: "192.168.127.140"

可以发现,错误日志中记录了limiting requests的zone为req_zone,即我们配置的请求限制。我们修改一下配置,添加burst参数:

  • limit_conn_zone $binary_remote_addr zone=conn_zone:1m;
  • limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;
  • server {
  • listen 80;
  • server_name localhost;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • # 用于请求限制
  • location / {
  • root /opt/app/code/;
  • limit_req zone=req_zone burst=3 nodelay;
  • # limit_req zone=req_zone;
  • index index.html index.htm;
  • }

这个参数值为3时表示当收到的请求频率过高时,会对限制访问请求中前3个进行延迟响应,其他的请求将直接返回503错误。配置完后软重启Nginx,然后重新压测:

  • [root@centos ~]# ab -n 50 -c 20 http://192.168.127.140/1.html
  • This is ApacheBench, Version 2.3 <$Revision: 655654 $>
  • Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
  • Licensed to The Apache Software Foundation, http://www.apache.org/
  • Benchmarking 192.168.127.140 (be patient).....done
  • Server Software: nginx/1.13.8
  • Server Hostname: 192.168.127.140
  • Server Port: 80
  • Document Path: /1.html
  • Document Length: 158 bytes
  • Concurrency Level: 20
  • Time taken for tests: 0.011 seconds
  • Complete requests: 50
  • Failed requests: 46
  • (Connect: 0, Receive: 0, Length: 46, Exceptions: 0)
  • Write errors: 0
  • Non-2xx responses: 46
  • Total transferred: 35186 bytes
  • HTML transferred: 25334 bytes
  • Requests per second: 4507.35 [#/sec] (mean)
  • Time per request: 4.437 [ms] (mean)
  • Time per request: 0.222 [ms] (mean, across all concurrent requests)
  • Transfer rate: 3097.57 [Kbytes/sec] received
  • Connection Times (ms)
  • min mean[+/-sd] median max
  • Connect: 0 0 0.3 0 1
  • Processing: 1 3 1.1 3 5
  • Waiting: 0 3 1.1 3 5
  • Total: 2 4 0.9 4 5
  • Percentage of the requests served within a certain time (ms)
  • 50% 4
  • 66% 4
  • 75% 4
  • 80% 5
  • 90% 5
  • 95% 5
  • 98% 5
  • 99% 5
  • 100% 5 (longest request)

可以发现,这次的50个请求中,有46个请求是失败的,由于我们配置了访问限制的速率为rate=1r/s,所以会响应一个请求,然后会对接下来的3个请求进行延迟响应,所以有4个请求是成功的:

  • Complete requests: 50
  • Failed requests: 46
  • (Connect: 0, Receive: 0, Length: 46, Exceptions: 0)
  • Write errors: 0
  • Non-2xx responses: 46

5. Nginx的访问控制

Nginx的访问控制有两种:

  • 基于IP的访问控制:http_access_module;
  • 基于用户的信任登录:http_auth_basic_module;

分别介绍如下:

5.1. http_access_module的配置

该配置的基本语法如下:

  • 允许访问的配置
  • 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

例如我们有以下配置:

  • server {
  • listen 80;
  • server_name localhost;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • location / {
  • root /opt/app/code;
  • index index.html index.htm;
  • }
  • location ~ ^/admin.html {
  • root /opt/app/code;
  • deny 192.168.1.6;
  • allow all;
  • index index.html index.htm;
  • }
  • ...

这个配置将在收到/admin.html开头的请求时,对IP为192.168.1.6的地址做限制,其他的IP访问不做限制。

  • server {
  • listen 80;
  • server_name localhost;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • location / {
  • root /opt/app/code;
  • index index.html index.htm;
  • }
  • location ~ ^/admin.html {
  • root /opt/app/code;
  • allow 192.168.1.1/254;
  • deny all;
  • index index.html index.htm;
  • }
  • ...

而上面的配置将只允许192.168.1.1~192.168.1.254的网段IP访问。

5.2. http_auth_basic_module的配置

该配置的基本语法如下:

  • 以显示字符串的形式开启:
  • 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

Nginx官方规定我们以一定的格式来书写密码文件,并且推荐我们使用htpasswd工具。

注:htpasswd在httpd-tools这个软件包中附带安装:

  • [root@localhost ~]# rpm -qf /usr/bin/htpasswd
  • httpd-tools-2.4.6-67.el7.centos.6.x86_64

我们进行如下的配置:

  • server {
  • listen 80;
  • server_name localhost;
  • #charset koi8-r;
  • #access_log /var/log/nginx/host.access.log main;
  • location / {
  • root /opt/app/code;
  • index index.html index.htm;
  • }
  • location ~ /admin.html {
  • root /opt/app/code;
  • auth_basic "Auth access test! input your password";
  • auth_basic_user_file /etc/nginx/auth_conf;
  • index index.html index.htm;
  • }
  • ...

在上述配置中,指定了auth_basic以配置提示用户的信息;然后使用auth_basic_user_file指定了验证用户名和密码的文件,这个文件是位于/etc/nginx/目录下的auth_conf文件。我们可以使用htpasswd来生成一些用户和密码到这个文件中:

  • [root@localhost nginx]# htpasswd -c ./auth_conf jack
  • New password:
  • Re-type new password:
  • Adding password for user jack
  • [root@localhost nginx]# cat auth_conf
  • jack:$apr1$OpIOYkVf$BwN8.d8t4VCjBYgm6b9071

重启Nginx后,访问相应的页面会有如下的提示:

1.4.http_auth_basic_module访问演示

会发现浏览器提示我们需要进行身份验证,输入刚刚创建的用户名和密码就可以进行访问了。

http_auth_basic_module的方式是有一定的局限性的,它的用户信息依赖于文件的形式存放,同时其操作管理效率较低;一般来说,我们可以使用Nginx结合LUA或者Nginx与LDAP打通,利用nginx-auth-ldap模块来实现高效验证。