centos7源码编译安装nginx1.19并调优,向已安装的nginx添加新模块

一.关于nginx

​ nginx是由1994年毕业于俄罗斯国立莫斯科鲍曼科技大学的同学为俄罗斯rambler.ru公司开发的,开发工作最早从2002年开始,第一次

公开发布时间是2004年10月4日,版本号是0.1.0

 Nginx是单进程单线程模型,即启动的工作进程只有一个进程响应客户端请求,不像apache可以在一个进程内启动多个线程响应请求,

因此在内存占用上比apache小很多。Nginx维持一万个非活动会话只要2.5M内存。Nginx和MySQL是CPU密集型的,就是对CPU的占用比

较大,默认session在本地文件保存,支持将session保存在memcache,但是memcache默认支持最大1M的hash对象。

nginx的版本分为开发版、稳定版和过期版,nginx以功能丰富著称,它即可以作为http服务器,也可以作为反向代理服务器或者邮件

服务器,能够快速的响应静态网页的请求,支持FastCGI/SSL/Virtual Host/URL Rwrite/Gzip/HTTP Basic Auth等功能,并且支持第三方的

功能扩展。

二.nginx的安装方式

​ nginx安装可以使用yum或源码安装,推荐使用源码,一是yum的版本比较旧,二是使用源码可以自定义功能,方便业务的上的使用。

​ 源码安装需要提前准备标准的编译器,GCC的全称是(GNU Compiler collection),其由GNU开发,并以GPL即LGPL许可,是自由的

类UNIX即苹果电脑Mac OS X操作系统的标准编译器,因为GCC原本只能处理C语言,所以原名为GNU C语言编译器,后来得到快速发

展,可以处理C++,Fortran,pascal,objective-C,Java以及Ada等其他语言,此外还需要Automake工具,以完成自动创建Makefile的工

作,Nginx的一些模块需要依赖第三方库,比如pcre(支持rewrite),zlib(支持gzip模块)和openssl(支持ssl模块)。

三.源码编译安装nginx

3.1 下载nginx源码并解压

[root@node5 ~]# wget http://nginx.org/download/nginx-1.19.3.tar.gz 
[root@node5 ~]# ls nginx-1.19.3.tar.gz -lh
-rw-r--r-- 1 root root 1.1M Sep 29 22:39 nginx-1.19.3.tar.gz
[root@node5 ~]# tar xf nginx-1.19.3.tar.gz 
[root@node5 ~]# cd nginx-1.19.3
[root@node5 nginx-1.19.3]# pwd
/root/nginx-1.19.3
[root@node5 nginx-1.19.3]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src

3.2 创建nginx用户和组

[root@node5 nginx]# groupadd nginx
[root@node5 nginx]# useradd -g nginx nginx

[root@node5 nginx]# id nginx
uid=8000(nginx) gid=8000(nginx) groups=8000(nginx)

[root@node5 nginx]# grep nginx /etc/passwd
nginx:x:8000:8000::/home/nginx:/bin/bash

#设置linux高负载参数,调整文件描述符
[root@node5 nginx]# ulimit -SHn 65535

3.3 安装nginx编译环境(解决依赖问题)

nginx编译需要的组件介绍:

​ gcc为GNU Compiler Collection的缩写,可以编译C和C++源代码等,它是GNU开发的C和C++以及其他很多种语言 的编译器(最早的

时候只能编译C,后来很快进化成一个编译多种语言的集合,如Fortran、Pascal、Objective-C、Java、Ada、 Go等。)

​ gcc 在编译C++源代码的阶段,只能编译 C++ 源文件,而不能自动和 C++ 程序使用的库链接(编译过程分为编译、链接两个阶段,注意

不要和可执行文件这个概念搞混,相对可执行文件来说有三个重要的概念:编译(compile)、链接(link)、加载(load)。源程序文

件被编译成目标文件,多个目标文件连同库被链接成一个最终的可执行文件,可执行文件被加载到内存中运行)。因此,通常使用 g++ 命

令来完成 C++ 程序的编译和连接,该程序会自动调用 gcc 实现编译。

​ gcc-c++也能编译C源代码,只不过把会把它当成C++源代码,后缀为.c的,gcc把它当作是C程序,而g++当作是c++程序;后缀为.cpp

的,两者都会认为是c++程序,注意,虽然c++是c的超集,但是两者对语法的要求是有区别的。

​ automake是一个从Makefile.am文件自动生成Makefile.in的工具。为了生成Makefile.in,automake还需用到perl,由于automake创

建的发布完全遵循GNU标准,所以在创建中不需要perl。libtool是一款方便生成各种程序库的工具。

​ pcre pcre-devel:在Nginx编译时,需要 PCRE(Perl Compatible Regular Expression),因为Nginx 的Rewrite模块和HTTP 核心模块会

使用到PCRE正则表达式语法。pcre-devel 是使用 pcre 开发的一个二次开发库。

​ zlip zlib-devel:zlib 库提供了很多种压缩和解压缩的方式, nginx 使用 zlib 对 http 包的内容进行 gzip ,所以需要在 Centos 上安装

zlib 库。nginx启用压缩功能的时候,需要此模块的支持。

​ openssl openssl-devel:OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及 SSL

协议,并提供丰富的应用程序供测试或其它目的使用。nginx 不仅支持 http 协议,还支持 https(即在ssl协议上传输http)。开启SSL的

时候需要此模块的支持。

[root@node5 ~]# yum -y install gcc gcc-c++ automake pcre pcre-devel zlip zlib-devel openssl openssl-devel 
Loaded plugins: fastestmirror
......
Package 1:openssl-1.0.2k-19.el7.x86_64 already installed and latest version
Package 1:openssl-devel-1.0.2k-19.el7.x86_64 already installed and latest version
Nothing to do

3.4 检查系统环境

​ 检查系统环境是否符合编译安装的要求,比如是否有gcc编译工具,是否支持编译参数当中的模块,并根据开启的参数等生成Makefile

文件为下一步做准备:

[root@node5 nginx-1.19.3]# pwd
/root/nginx-1.19.3
[root@node5 nginx-1.19.3]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@node5 nginx-1.19.3]# ./configure  --prefix=/usr/local/nginx  --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log  --http-log-path=/var/log/nginx/access.log  --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock  --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre
checking for OS
 + Linux 3.10.0-693.el7.x86_64 x86_64
checking for C compiler ... found
......
  nginx http uwsgi temporary files: "/var/tmp/nginx/uwsgi"
  nginx http scgi temporary files: "/var/tmp/nginx/scgi"

#echo $?输出为0,则上一步骤没错
[root@node5 nginx-1.19.3]# echo $?
0

3.5 编译nginx

[root@node5 nginx-1.19.3]# make -j 4
[root@node5 nginx-1.19.3]# echo $?
0

3.6 编译安装nginx

[root@node5 nginx-1.19.3]# make install

[root@node5 nginx-1.19.3]# echo $?
0

3.7 启动nginx

[root@node5 nginx-1.19.3]# cd /usr/local/nginx/
[root@node5 nginx]# ls
conf  html  sbin
[root@node5 nginx]# pwd
/usr/local/nginx

#查看nginx详细版本信息
[root@node5 nginx]# sbin/nginx -V
nginx version: nginx/1.19.3
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 --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-te  -path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi -▽with-pcre

#启动nginx报错,需要创建/var/tmp/nginx/client/目录
[root@node5 nginx]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx: [emerg] mkdir() "/var/tmp/nginx/client/" failed (2: No such file or directory)

[root@node5 nginx]# su nginx

[nginx@node5 nginx]$ mkdir -p /var/tmp/nginx/client/
[nginx@node5 nginx]$ exit
exit
#再次启动nginx
[root@node5 nginx]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

#可以看到nginx启动成功
#master process是nginx的主进程,只有一个主进程
#worker process是nginx工作进程,默认只有一个,可以通过修改nginx.conf中的worker_processes  1; 参数启动多个工作进程
[root@node5 nginx]# ps -ef | grep nginx
root      14592      1  0 16:33 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     14593  14592  0 16:33 ?        00:00:00 nginx: worker process
root      14604 128012  0 16:33 pts/1    00:00:00 grep --color=auto nginx

#停止nginx
[root@node5 nginx]# /usr/local/nginx/sbin/nginx -s stop

[root@node5 nginx]# ps -ef | grep nginx
root      14765 128012  0 16:36 pts/1    00:00:00 grep --color=auto nginx

3.8 nginx目录功能介绍:

  • ​ conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有个模板配置文件,是文件名.default结尾,使用时复制一份,去掉default后缀即可。
  • ​ html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。
  • ​ logs:用来保存nginx服务器的访问日志,错误日志等日志,logs目录可以放在其他路径,比如/var/logs/nginx里面。
  • ​ sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。
[root@node5 ~]# cd /usr/local/nginx/
[root@node5 nginx]# pwd
/usr/local/nginx
[root@node5 nginx]# ls
conf  html  sbin

[root@node5 nginx]# ls conf/
fastcgi.conf          fastcgi_params          koi-utf  mime.types          nginx.conf          scgi_params          uwsgi_params          win-utf
fastcgi.conf.default  fastcgi_params.default  koi-win  mime.types.default  nginx.conf.default  scgi_params.default  uwsgi_params.default

[root@node5 nginx]# ls html/
50x.html  index.html

[root@node5 nginx]# ls sbin/
nginx

[root@node5 nginx]# ls /var/log/nginx
access.log  error.log

四.设置nginx开机自启动

​ 设置nginx开机自启动,并使用systemctl管理,此步骤有两种方法,任选一种即可

方法一:

#创建软链接
[root@node5 nginx]# ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx
[root@node5 nginx]# ll /usr/bin/nginx 
lrwxrwxrwx 1 root root 27 Oct 22 16:43 /usr/bin/nginx -> /usr/local/nginx/sbin/nginx

[root@node5 nginx]# vim /etc/init.d/nginx

#/etc/init.d/nginx的内容如下
[root@node5 ~]# cat /etc/init.d/nginx
#!/bin/bash
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /usr/local/nginx/conf/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
#lockfile=/var/lock/subsys/nginx
lockfile=/var/lock/nginx.lock
make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
force_reload() {
    restart
}
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
    status $prog
}
rh_status_q() {
    rh_status >/dev/null 2>&1
}
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac
[root@node5 ~]# 

#/etc/init.d/nginx给脚本赋予可执行权限
[root@node5 nginx]# chmod a+x /etc/init.d/nginx

[root@node5 nginx]# ll !$
ll /etc/init.d/nginx
-rwxr-xr-x 1 root root 2649 Oct 22 17:48 /etc/init.d/nginx

[root@node5 nginx]# chkconfig --add /etc/init.d/nginx
[root@node5 nginx]# chkconfig nginx on

#启动nginx
[root@node5 nginx]# systemctl start nginx

#查看nginx启动状态
[root@node5 nginx]# ps -ef | grep nginx
root      18530      1  0 17:49 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     18531  18530  0 17:49 ?        00:00:00 nginx: worker process
root      18547 128012  0 17:50 pts/1    00:00:00 grep --color=auto nginx

#查看nginx启动状态
[root@node5 nginx]# systemctl status nginx
● nginx.service - SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server
   Loaded: loaded (/etc/rc.d/init.d/nginx; bad; vendor preset: disabled)
   Active: active (running) since Thu 2020-10-22 17:49:55 CST; 1min 24s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 18434 ExecStart=/etc/rc.d/init.d/nginx start (code=exited, status=0/SUCCESS)
 Main PID: 18530 (nginx)
   CGroup: /system.slice/nginx.service
           ├─18530 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
           └─18531 nginx: worker process

Oct 22 17:49:55 node5 systemd[1]: Starting SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server...
Oct 22 17:49:55 node5 nginx[18434]: Starting nginx: [  OK  ]
Oct 22 17:49:55 node5 systemd[1]: Started SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server.

#停止nginx
[root@node5 nginx]# systemctl stop nginx
 
[root@node5 nginx]# systemctl status nginx
● nginx.service - SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server
   Loaded: loaded (/etc/rc.d/init.d/nginx; bad; vendor preset: disabled)
   Active: inactive (dead) since Thu 2020-10-22 17:51:29 CST; 4s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 18623 ExecStop=/etc/rc.d/init.d/nginx stop (code=exited, status=0/SUCCESS)
  Process: 18434 ExecStart=/etc/rc.d/init.d/nginx start (code=exited, status=0/SUCCESS)
 Main PID: 18530 (code=exited, status=0/SUCCESS)

Oct 22 17:49:55 node5 systemd[1]: Starting SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server...
Oct 22 17:49:55 node5 nginx[18434]: Starting nginx: [  OK  ]
Oct 22 17:49:55 node5 systemd[1]: Started SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server.
Oct 22 17:51:29 node5 systemd[1]: Stopping SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server...
Oct 22 17:51:29 node5 nginx[18623]: Stopping nginx: [  OK  ]
Oct 22 17:51:29 node5 systemd[1]: Stopped SYSV: NGINX is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server.

[root@node5 nginx]# ps -ef | grep nginx
root      18649 128012  0 17:51 pts/1    00:00:00 grep --color=auto nginx

方法二:

[root@node5 nginx]# vim /usr/lib/systemd/system/nginx.service
 
[Unit]
Description=The nginx HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
 
[Service]
Type=forking
PIDFile=/var/run/nginx/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP /var/run/nginx/nginx.pid
ExecStop=/bin/kill -s QUIT /var/run/nginx/nginx.pid
PrivateTmp=true
 
[Install]
WantedBy=multi-user.target

#加入开机自启动并启动Nginx
[root@node5 nginx]# systemctl enable nginx.service
[root@node5 nginx]# systemctl restart nginx.service

五.测试nginx功能是否正常

#能出现如下输出则nginx成功启动
[root@node5 nginx]# curl 192.168.110.184:80
<!DOCTYPE html>
<html>
<head>
......
<p><em>Thank you for using nginx.</em></p>
</body>
</html>

直观一点的话可以查看浏览器

image-20201022181503533

六.开放防火墙里的80端口

如果防火墙启动了的话,需要设置Firewalld防火墙,把80端口开放了

#启动防火墙
[root@node5 nginx]# systemctl start firewalld
[root@node5 nginx]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: active (running) since Thu 2020-10-22 18:17:11 CST; 1s ago
     Docs: man:firewalld(1)
 Main PID: 20056 (firewalld)
   CGroup: /system.slice/firewalld.service
           └─20056 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

Oct 22 18:17:11 node5 systemd[1]: Starting firewalld - dynamic firewall daemon...
Oct 22 18:17:11 node5 systemd[1]: Started firewalld - dynamic firewall daemon.
Oct 22 18:17:11 node5 firewalld[20056]: WARNING: ICMP type 'beyond-scope' is not supported by the kernel for ipv6.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: beyond-scope: INVALID_ICMPTYPE: No supported ICMP type., ignoring for run-time.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: ICMP type 'failed-policy' is not supported by the kernel for ipv6.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: failed-policy: INVALID_ICMPTYPE: No supported ICMP type., ignoring for run-time.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: ICMP type 'reject-route' is not supported by the kernel for ipv6.
Oct 22 18:17:12 node5 firewalld[20056]: WARNING: reject-route: INVALID_ICMPTYPE: No supported ICMP type., ignoring for run-time.

#把80端口开放
[root@node5 nginx]# firewall-cmd --zone=public --add-port=80/tcp --permanent
success
[root@node5 nginx]# firewall-cmd --reload
success

[root@node5 nginx]# curl 192.168.110.184:80

如果完成防火墙设置以后,浏览器还能访问nginx页面,说明设置成功。

七.nginx日志切割

方法一:

1.nginx默认不会自动切割日志文件,可以使用shell脚本配合crontab进行自动切割日志。

2.日志切割脚本中用到一个命令:kill -USR1 nginx的主进程号 。该命令的作用是:向nginx主进程发送USR1信号,nginx主进程接到信号

后会从配置文件中读取日志文件名称,重新打开日志文件 (以配置文件中的日志名称命名) ,并以工作进程的用户作为日志文件的所有者重

新打开日志文件后,nginx主进程会关闭重名的日志文件并通知工作进程使用新打开的日志文件。工作进程立刻打开新的日志文件并关闭

重名名的日志文件,然后你就可以处理旧的日志文件了。

3.编写日志切割脚本

#切割日志的脚本如下
[root@node5 ~]# cat nginx_log_rotate.sh 
#!/bin/bash
#脚本执行,遇到错就退出,不再往下执行
set -e
# 配合定时任务,0点过一秒再开始切割任务
sleep 1
#查询nginx主进程号
PID=`cat /var/run/nginx/nginx.pid`
#获得服务器昨天的时间
yesterday=$(date -d 'yesterday' +%Y-%m-%d)
#nginx的日志文件目录
ng_logs_dir='/var/log/nginx/'
#判断nginx日志目录是否存在,存在则进行日志切割
if [ -d $ng_logs_dir ];then
  cd $ng_logs_dir
  #通过 mv 命令将日志移动到分割后的日志,error日志一般不做切割
  mv access.log  access_${yesterday}.log
  #发送 kill -USR1 信号给 Nginx 的主进程号,让 Nginx 重新生成一个新的日志文件
  kill -USR1 $PID
  sleep 1
  #把旧的日志打成压缩包
  tar -czf  access_${yesterday}.log.tar.gz access_${yesterday}.log
  #已有压缩包,删除压缩前的日志
  rm -f  access_${yesterday}.log
else
  echo "nginx日志目录不存在,请检查"
  exit 0
fi
 
#赋予脚本可执行权限
[root@node5 ~]# chmod +x nginx_log_rotate.sh 

[root@node5 ~]# ll nginx_log_rotate.sh 
-rwxr-xr-x 1 root root 951 Oct 26 15:36 nginx_log_rotate.sh

[root@node5 ~]# ll -h /var/log/nginx/
-rw-r--r-- 1 nginx root  11K Oct 26 15:37 access.log
-rw-r--r-- 1 nginx root  554 Oct 22 17:51 error.log
 
#手动执行脚本查看效果
[root@node5 ~]# bash nginx_log_rotate.sh 
 
[root@node5 ~]# ll -h /var/log/nginx/
-rw-r--r-- 1 root  root  418 Oct 26 15:37 access_2020-10-25.log.tar.gz
-rw-r--r-- 1 nginx root    0 Oct 26 15:37 access.log
-rw-r--r-- 1 nginx root  554 Oct 22 17:51 error.log
 

4.设置crontab定时任务,每天凌晨执行脚本

[root@node5 ~]# crontab -e

[root@node5 ~]# crontab -l
0 0 * * * bash /root/nginx_log_rotate.sh

方法二:

#nginx日志切割脚本如下
[root@node5 ~]# cat logqiege.sh 
#!/bin/bash
PID=`cat /var/run/nginx/nginx.pid`
mv   /var/log/nginx/access.log   /var/log/nginx/`date  +%Y_%m_%d:%H:%M:%S`.access.log
kill -USR1 $PID

[root@node5 ~]# chmod +x logqiege.sh 

[root@node5 ~]# ll -h /var/log/nginx/
total 20K
-rw-r--r-- 1 nginx root 14K Oct 26 15:58 access.log
-rw-r--r-- 1 nginx root 554 Oct 22 17:51 error.log
 
[root@node5 ~]# bash logqiege.sh 

[root@node5 ~]# ll -h /var/log/nginx/
total 20K
-rw-r--r-- 1 nginx root 14K Oct 26 15:58 2020_10_26:15:58:38.access.log
-rw-r--r-- 1 nginx root   0 Oct 26 15:58 access.log
-rw-r--r-- 1 nginx root 554 Oct 22 17:51 error.log

[root@node5 ~]# crontab -e

[root@node5 ~]# crontab -l
*/1 * * * * bash /root/logqiege.sh

方法三:

1.高级用法–使用 nginx 本身来实现
当 nginx 在容器里,把 nginx 日志挂载出来的时候,我们发现就不适合再使用 kill -USR1 的方式去分割日志,这时候当然就需要从 nginx

本身配置去解决这个问题了,我们都知道访问日志里面都有一个时间相关的字段,如果我们把这个时间捞出来,这个问题就解决了

我们来看按天生成访问日志

 if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") {
            set $year $1;
            set $month $2;
            set $day $3;
     }
     access_log /var/log/nginx/${year}_${month}_${day}_access.log json;


#或者脚本也可以这么写
#切割日志 
         if ($time_iso8601 ~ '(\d{4}-\d{2}-\d{2})') {
               set $tttt $1;
          }
         access_log  /home/wwwlogs/access-$tttt.log ;     

查看日志生成的结果

image-20201026163320375

2.看到日志已经按照我们的需求切割出来了,这个的日志切割可以达到秒级,用法都是一样的,去正则匹配到时间戳就好了。nginx 内置

的变量有很多,列如 ${server_name} 这些变量都是可以用来命名日志,当然如果我们需要压缩,就写个对应的定时任务去做压缩就好了。

八.给nginx主进程发送信号进行nginx的停止,升级,日志切割

1.获取nginx主进程号的办法:

#获取nginx主进程号的办法:方法一
[root@node5 ~]# ps -ef | grep nginx
root      19806      1  0 Oct23 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     19807  19806  0 Oct23 ?        00:00:00 nginx: worker process
root      97457  77960  0 17:01 pts/7    00:00:00 grep --color=auto nginx

#获取nginx主进程号的办法:方法二:
#查看nginx的pid文件,此文件保存的就是nginx的主进程id,此ID是随机的,每次启动都不一样的
[root@node5 ~]# cat /var/run/nginx/nginx.pid
19806

2.nginx支持的信号如下

#nginx支持的信号:
#平缓关闭Nginx,即不再接受新的请求,但是等当前请求处理完毕后再关闭Nginx。
[root@node5 ~]# kill  -QUIT 19806  

#快速停止Nginx服务
[root@node5 ~]# kill  -TERM  19806 

#使用新的配置文件启动进程然后平缓停止原有的nginx进程,即平滑重启。 
[root@node5 ~]# kill  -HUP 19806 

#重新打开配置文件,用于nginx 日志切割,关于具体的日志切割技巧请查看“nginx日志切割”章节
[root@node5 ~]# kill -USR1 19806   

#使用新版本的nginx文件启动服务,然后在平缓停止原有的nginx服务,即平滑升级。
[root@node5 ~]# kill -USR2 21703  

#平滑停止nginx的工作进程,用于nginx平滑升级。
[root@node5 ~]# kill -WINCH  21703  

#Nginx,-s采用向 Nginx发送信号的方式,-s signal:send signal to a master process: stop, quit, reopen, reload
#此方式停止步骤是待nginx进程处理任务完毕进行停止。
[root@node5 ~]# nginx -s quit
#此方式相当于先查出nginx进程id再使用kill命令强制杀掉进程。
[root@node5 ~]# nginx -s stop

九.nginx常用命令

下面列举了nginx经常使用到的命令

#查看Nginx的版本号
[root@node5 ~]# /usr/local/nginx/sbin/nginx -v
nginx version: nginx/1.19.3

#查看Nginx的版本号和编译参数
[root@node5 ~]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.19.3
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 --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre


#启动nginx:nginx安装目录地址 -c nginx配置文件地址
#-c后指定nginx的配置文件
[root@node5 ~]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

#验证nginx配置文件是否正确
[root@node5 ~]# /usr/local/nginx/sbin/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

#Nginx,-s采用向 Nginx发送信号的方式,-s signal:send signal to a master process: stop, quit, reopen, reload
#此方式停止步骤是待nginx进程处理任务完毕进行停止。
[root@node5 ~]# nginx -s quit
#此方式相当于先查出nginx进程id再使用kill命令强制杀掉进程。
[root@node5 ~]# nginx -s stop

#Nginx重新加载配置文件,-s采用向 Nginx发送信号的方式
nginx -s reload


#nginx停止操作是通过向nginx进程发送信号来进行的
#步骤1:查询nginx主进程号
ps -ef | grep nginx
#在进程列表里 面找master进程,它的编号就是主进程号了。
#步骤2:发送信号
#从容停止Nginx:
kill -QUIT 主进程号
#快速停止Nginx:
kill -TERM 主进程号
#强制停止Nginx:
pkill -9 nginx
#若在nginx.conf配置了nginx.pid文件存放路径,则nginx.pid存放的就是Nginx主进程号,如果没指定,则默认放在nginx的logs目录下,有了nginx.pid文件,我们就不用查询Nginx的主进程号,再杀进程了。可以直接向Nginx发送信号了,
#命令如下:kill -信号类型 '/usr/nginx/logs/nginx.pid'
[root@node5 ~]# kill -9 /var/run/nginx/nginx.pid


# 启动
systemctl start nginx
# 查看状态
systemctl status nginx
# 停止
systemctl stop nginx

十.nginx配置文件详解

1.nginx的主配置文件为nginx.conf,先看看nginx.conf的默认配置文件。#开头的都是注释。

#过滤配置文件中的注释和空行
[root@node5 ~]# egrep -v "#|^$" /usr/local/nginx/conf/nginx.conf
#nginx的启动用户/组
user  nginx;
#启动的工作进程数量,可以指定启动的固定nginx进程数,或使用auto,auto是启动与当前CPU线程相同的进程数,如CPU是四核八线程的就启动八个进程的Nginx工作进程。
worker_processes  2;
#错误日志路径
error_log  /var/log/nginx/error.log;
error_log  /var/log/nginx/error.log  notice;
error_log  /var/log/nginx/error.log  info;
#Nginx的PID路径
pid        /var/run/nginx/nginx.pid;

#events模块主要影响nginx服务器与用户的网络连接,比如是否允许同时接受多个网络连接,使用哪种事件驱动模型处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的网络连接进行序列化等。
events {
#设置nginx可以接受的最大并发数
    worker_connections  1024;
}

#http模块是Nginx服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模块都可以在这设置,http块可以包含多个server块,而一个server块中又可以包含多个location块,server块可以配置文件引入、MIME-Type定义、日志自定义、是否启用sendfile、连接超时时间和单个链接的请求上限等。
http {
#文件扩展名与文件类型映射表
    include       mime.types;
    #默认文件类型
    default_type  application/octet-stream;
    access_log  /var/log/nginx/access.log;
    #是否调用 sendfile 函数(zero copy -->零copy方式)来输出文件,普通应用打开,可以大幅提升nginx的读文件性能,如果服务器是下载的就需要关闭。
    sendfile        on;
    #长连接超时时间,单位是秒
    keepalive_timeout  65;
    #server模块,设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多个locating模块。比如本虚拟机监听的端口、本虚拟机的名称和IP配置,多个server 可以使用一个端口,比如都使用80端口提供web服务。
    server {
    #server的全局配置,配置监听的端口
        listen       80;
        #server的名称,当访问此名称的时候,nginx会调用当前serevr内部的配置进程匹配。
        server_name  localhost;
        #location其实是server的一个指令,为nginx服务器提供比较多而且灵活的指令,都是在location中体现的,主要是基于nginx接受到的请求字符串,对用户请求的URL进行匹配,并对特定的指令进行处理,包括地址重定向、数据缓存和应答控制等功能都是在这部分实现,另外很多第三方模块的配置也是在location模块中配置。
        location / {
        #相当于默认页面的目录名称,默认是相对路径,可以使用绝对路径配置。
            root   html;
            index  index.html index.htm;
        }
        #错误页面的文件名称
        error_page   500 502 503 504  /50x.html;
        #location处理对应的不同错误码的页面定义到/50x.html,这个对应其server中定义的目录下。
        location = /50x.html {
        #定义默认页面所在的目录
            root   html;
        }
    }
}
        

2.绑定Nginx的工作进程到不同的CPU上,默认Nginx是不进行绑定的,绑定并不是当前nginx进程独占一核心CPU,但是可以保证此进程不会运行在其他核心上,这就极大减少了nginx 工作进程在不同cpu上的跳转,减少了CPU对进程的资源分配与回收,因此可以有效的提升nginx服务器的性能,配置如下:

#查看CPU的核心数量
[root@node5 ~]# grep process /proc/cpuinfo  | wc -l
4

#四个线程CPU的配置:
worker_processes  4; 
worker_cpu_affinity 0001 0010 0100 1000;

#八个线程CPU的配置:
worker_processes  8; 
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

3.nginx的PID文件,错误日志文件路径,日志记录级别相关配置:

#指定nginx的PID文件路径
pid        logs/nginx.pid;   
#指定错误日志路径
error_log  logs/error.log;  
#指定日志记录级别
error_log  logs/error.log  notice;  
error_log  logs/error.log  info;

#nginx支持的日志级别:
#日志级别语法:
error_log file [ debug | info | notice | warn | error | crit ]  | [{  debug_core | debug_alloc | debug_mutex | debug_event | debug_http | debug_mail | debug_mysql } ]
日志级别 = 错误日志级别 | 调试日志级别; 或者
日志级别 = 错误日志级别;
#crit 记录的日志最少,而debug记录的日志最多。如果你的nginx遇到一些问题,比如502比较频繁出现,但是看默认的error_log并没有看到有意义的信息,那么就可以调一下错误日志的级别,当你调成error级别时,错误日志记录的内容会更加丰富。
#错误日志的级别: emerg, alert, crit, error, warn, notic, info, debug, 
#调试日志的级别: debug_core, debug_alloc, debug_mutex, debug_event, debug_http, debug_mail, debug_mysql



#error_log 指令的日志级别配置分为错误日志级别和调试日志级别,错误日志只能设置一个级别,而且错误日志必须书写在调试日志级别的前面,另外调试日志可以设置多个级别,其他配置方法可能无法满足需求。

4.配置文件的引入:include

#file是要导入的文件,支持相对路径,一般在html目录里面
include file; 

#例如:导入一个conf文件,并配置不同主机名的页面,编辑nginx.conf主配置文件:
#在最后一个大括号里面加入一项,*是导入任何以conf结尾的配置文件
include  /usr/local/nginx/conf.d/samsung.conf;  

#在/usr/local/nginx/conf.d/创建一个samsung.conf,内容如下:
[root@node5 ~]# grep -v "#" conf.d/samsung.conf  | grep -v "^$"
    server {
        listen       8090;
        server_name  samsung.chinacloudapp.cn;
        location / {
            root   html;
            index  index1.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

十一.nginx性能调优

1.主配置文件nginx.conf优化

#nginx的启动用户/组
user nginx nginx;

#nginx进程数,建议按照cpu数目来指定,一般为它的倍数。
worker_processes 8;
#为每个进程分配cpu,将8个进程分配到8个cpu,当然可以写多个,或者将一个进程分配到多个cpu。
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000;

error_log  /usr/local/nginx/logs/nginx_error.log  crit;

pid        /usr/local/nginx/logs/nginx.pid;

#这个指令是指一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n的值保持一致。
#注:这里需要设置 ulimit -SHn 204800
worker_rlimit_nofile 204800;

events
{
#使用epoll的I/O模型
 use epoll;
 #每个进程允许的最多连接数,理论上每台nginx服务器的最大连接数为worker_processes*worker_connections
 worker_connections 204800;
}

http {
      include      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"';
      access_log  logs/access.log  main;
      charset  utf-8;
      server_names_hash_bucket_size 128;
      #客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求的头部大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE取得。
      client_header_buffer_size 32k;
      large_client_header_buffers 4 32k;
      client_max_body_size 20m;

      sendfile on;
      tcp_nopush on;

#keepalive超时时间
      keepalive_timeout 60;

      fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2
                        keys_zone=TEST:10m
                        inactive=5m;
      fastcgi_connect_timeout 300;
      fastcgi_send_timeout 300;
      fastcgi_read_timeout 300;
      fastcgi_buffer_size 64k;
      fastcgi_buffers 4 64k;
      fastcgi_busy_buffers_size 128k;
      fastcgi_temp_file_write_size 128k;

#这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive是指经过多长时间文件没被请求后删除缓存。
      open_file_cache max=204800 inactive=20s;
      #open_file_cache指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive时间内一次没被使用,它将被移除。
      open_file_cache_min_uses 1;
      #这个是指多长时间检查一次缓存的有效信息。
      open_file_cache_valid 30s;

      tcp_nodelay on;

      gzip on;
      gzip_min_length  1k;
      gzip_buffers    4 16k;
      gzip_http_version 1.0;
      gzip_comp_level 2;
      gzip_types      text/plain application/x-javascript text/css application/xml;
      gzip_vary on;
}

2.内核参数的优化

#备份初始内核参数
[root@node5 ~]# cp /etc/sysctl.conf /etc/sysctl.conf.bak

#清空内核参数
[root@node5 ~]# > /etc/sysctl.conf

#配置内核参数
[root@node5 ~]# vi /etc/sysctl.conf

net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
#开启SYN Cookies,当出现SYN等待队列溢出时,启用cookies来处理。
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
#timewait的数量,默认是180000。
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096        87380  4194304
net.ipv4.tcp_wmem = 4096        16384  4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
#每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。
net.core.netdev_max_backlog = 262144
#web应用中listen函数的backlog默认会给我们内核参数的net.core.somaxconn限制到128,而nginx定义的NGX_LISTEN_BACKLOG默认为511,所以有必要调整这个值。
net.core.somaxconn = 262144
#系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤儿连接将即刻被复位并打印出警告信息。这个限制仅仅是为了防止简单的DoS攻击,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。
net.ipv4.tcp_max_orphans = 3276800
#记录的那些尚未收到客户端确认信息的连接请求的最大值。对于有128M内存的系统而言,缺省值是1024,小内存的系统则是128。
net.ipv4.tcp_max_syn_backlog = 262144
#时间戳可以避免序列号的卷绕。一个1Gbps的链路肯定会遇到以前用过的序列号。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉。
net.ipv4.tcp_timestamps = 0
#为了打开对端的连接,内核需要发送一个SYN并附带一个回应前面一个SYN的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK包的数量。
net.ipv4.tcp_synack_retries = 1
#在内核放弃建立连接之前发送SYN包的数量。
net.ipv4.tcp_syn_retries = 1
#启用timewait快速回收。
net.ipv4.tcp_tw_recycle = 1
#开启重用。允许将TIME-WAIT sockets重新用于新的TCP连接。
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
#如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2状态的时间。对端可以出错并永远不关闭连接,甚至意外当机。缺省值是60秒。2.2 内核的通常值是180秒,你可以按这个设置,但要记住的是,即使你的机器是一个轻载的WEB服务器,也有因为大量的死套接字而内存溢出的风险,FIN- WAIT-2的危险性比FIN-WAIT-1要小,因为它最多只能吃掉1.5K内存,但是它们的生存期长些。
net.ipv4.tcp_fin_timeout = 1
#当keepalive起用的时候,TCP发送keepalive消息的频度。缺省是2小时。
net.ipv4.tcp_keepalive_time = 30
#允许系统打开的端口范围
net.ipv4.ip_local_port_range = 1024    65000

#保存内核参数
[root@node5 ~]# sysctl -p

3.FastCGI参数优化

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10m inactive=5m;
这个指令为FastCGI缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。

fastcgi_connect_timeout 300;
指定连接到后端FastCGI的超时时间。

fastcgi_send_timeout 300;
向FastCGI传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI传送请求的超时时间。

fastcgi_read_timeout 300;
接收FastCGI应答的超时时间,这个值是指已经完成两次握手后接收FastCGI应答的超时时间。

fastcgi_buffer_size 16k;
指定读取FastCGI应答第一部分需要用多大的缓冲区,这里可以设置为fastcgi_buffers指令指定的缓冲区大小,上面的指令指定它将使用1个16k的缓冲区去读取应答的第一部分,即应答头,其实这个应答头一般情况下都很小(不会超过1k),但是你如果在fastcgi_buffers指令中指定了缓冲区的大小,那么它也会分配一个fastcgi_buffers指定的缓冲区大小去缓存。

fastcgi_buffers 16 16k;
指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答,如上所示,如果一个php脚本所产生的页面大小为256k,则会为其分配16个16k的缓冲区来缓存,如果大于256k,增大于256k的部分会缓存到fastcgi_temp指定的路径中,当然这对服务器负载来说是不明智的方案,因为内存中处理数据速度要快于硬盘,通常这个值的设置应该选择一个你的站点中的php脚本所产生的页面大小的中间值,比如你的站点大部分脚本所产生的页面大小为256k就可以把这个值设置为16 16k,或者4 64k 或者64 4k,但很显然,后两种并不是好的设置方法,因为如果产生的页面只有32k,如果用4 64k它会分配1个64k的缓冲区去缓存,而如果使用64 4k它会分配8个4k的缓冲区去缓存,而如果使用16 16k则它会分配2个16k去缓存页面,这样看起来似乎更加合理。

fastcgi_busy_buffers_size 32k;
这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers的两倍。


fastcgi_temp_file_write_size 32k;
在写入fastcgi_temp_path时将用多大的数据块,默认值是fastcgi_buffers的两倍。

fastcgi_cache TEST
开启FastCGI缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU负载,并且防止502错误。但是这个缓存会引起很多问题,因为它缓存的是动态页面。具体使用还需根据自己的需求。

fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
为指定的应答代码指定缓存时间,如上例中将200,302应答缓存一小时,301应答缓存1天,其他为1分钟。

fastcgi_cache_min_uses 1;
缓存在fastcgi_cache_path指令inactive参数值时间内的最少使用次数,如上例,如果在5分钟内某文件1次也没有被使用,那么这个文件将被移除。

fastcgi_cache_use_stale error timeout invalid_header http_500;
不知道这个参数的作用,猜想应该是让nginx知道哪些类型的缓存是没用的。 以上为nginx中FastCGI相关参数,另外,FastCGI自身也有一些配置需要进行优化,如果你使用php-fpm来管理FastCGI,可以修改配置文件中的以下值:

<value name="max_children">60</value>
同时处理的并发请求数,即它将开启最多60个子线程来处理并发连接。

<value name="rlimit_files">102400</value>
最多打开文件数。

<value name="max_requests">204800</value>
每个进程在重置之前能够执行的最多请求数。

十二.nginx常见问题解决思路

12.1 普通用户启动,重启,重新加载nginx的时候报错:

1.当我们使用普通用户start,restart,reload nginx的时候出现如下错误:

nginx@node5 ~]$ /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /usr/local/nginx/conf/nginx.conf:1
nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)

2.出现这种问题的原因是:在Linux中1024以下的端口,只有root用户才有权限占用。

3.解决方法:

方法一:设置只有root和nginx的启动用户才能启动nginx(推荐)

#nginx用户为nginx的启动用户
[nginx@node5 ~]$ id nginx
uid=8000(nginx) gid=8000(nginx) groups=8000(nginx)

#设置nginx目录的所有者为root,组所有者为nginx
[root@node5 ~]# chown -R root:nginx /usr/local/nginx

[root@node5 ~]# ll /usr/local/nginx/ -d
drwxr-xr-x 5 root nginx 42 Oct 22 16:14 /usr/local/nginx/

[root@node5 ~]# chmod -R 750 /usr/local/nginx

#给可执行文件nginx设置SUID权限,这样nginx用户启动nginx的时候会临时获得root权限,关于SUID详解请查看“文件的特殊权限”章节
[root@node5 ~]# chmod u+s /usr/local/nginx/sbin/nginx 

[root@node5 ~]# su nginx

[nginx@node5 root]$ /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

#可以看到普通用户也可以启动nginx了
[nginx@node5 root]$ ps -ef | grep nginx
root      63296  61383  0 16:22 pts/0    00:00:00 su nginx
nginx     63297  63296  0 16:22 pts/0    00:00:00 bash
root      63345      1  0 16:23 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     63346  63345  0 16:23 ?        00:00:00 nginx: worker process
nginx     63347  63345  0 16:23 ?        00:00:00 nginx: worker process
nginx     63385  63297  0 16:24 pts/0    00:00:00 ps -ef
nginx     63386  63297  0 16:24 pts/0    00:00:00 grep --color=auto nginx
 
[nginx@node5 root]$ /usr/local/nginx/sbin/nginx -s quit

[nginx@node5 root]$ ps -ef | grep nginx
root      63296  61383  0 16:22 pts/0    00:00:00 su nginx
nginx     63297  63296  0 16:22 pts/0    00:00:00 bash
nginx     63470  63297  0 16:25 pts/0    00:00:00 ps -ef
nginx     63471  63297  0 16:25 pts/0    00:00:00 grep --color=auto nginx

方法二:设置所有用户都可以启动nginx(不推荐)

[root@node5 ~]# chown -R root:root /usr/local/nginx

[root@node5 ~]# chmod -R 755 /usr/local/nginx

[root@node5 ~]# chmod u+s /usr/local/nginx/sbin/nginx 

方法三:使用sudo管理员权限启动nginx,要执行此方法,必须保证nginx用户具有sudo权限,关于sudo权限配置详情,请查看“为普通用户配置sudo权限”章节

[nginx@node5 ~]$ sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

[nginx@node5 ~]$ ps -ef | grep nginx
root     111427  94811  0 15:46 pts/1    00:00:00 su - nginx
nginx    111428 111427  0 15:46 pts/1    00:00:00 -bash
root     111628      1  0 15:49 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx    111629 111628  0 15:49 ?        00:00:00 nginx: worker process
nginx    111630 111628  0 15:49 ?        00:00:00 nginx: worker process
nginx    111637 111428  0 15:49 pts/1    00:00:00 ps -ef
nginx    111638 111428  0 15:49 pts/1    00:00:00 grep --color=auto nginx

十三.向已安装的nginx添加新模块

13.1 问题背景

​ 一般来说,我们会按照项目需求和业务需求按需编译nginx,但是随着时间的推移,nginx已有的模块可能已经不能满足现有业务需求

了,此时就需要向nginx动态添加新模块,以满足需求。

13.2 向已经安装的nginx添加新模块

1.进行此步骤的前提条件:之前已经编译安装过nginx,并且现在正在运行。

2.向已安装的nginx添加新模块的思路:使用与现有nginx相同版本的源码包,添加新模块重新编译nginx源码,然后把编译好的nginx可执

行文件替换现有的nginx可执行文件。

3.nginx添加新模块的命令格式:

./configure 参数  --add-module=新模块

4.向已安装的nginx添加新模块,本次以添加ngx_http_google_filter_module模块为例,ngx_http_google_filter_module是一个过滤器模

块,能够让谷歌镜像更便捷的部署。内建了正则表达式、URI locations和其他复杂的配置。原生nginx模块确保了更加高效地处理

cookies, gstatic scoures和重定向。

#使用Git下载ngx_http_google_filter_module模块
[root@node5 ~]# git clone https://github.com/cuber/ngx_http_google_filter_module
[root@node5 ~]# git clone https://github.com/yaoweibin/ngx_http_substitutions_filter_module

#查看nginx的版本号和详细编译参数
[root@node5 ~]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.19.3
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 --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre

#解压和现有版本一模一样的nginx源码包
[root@node5 ~]# tar xf nginx-1.19.3.tar.gz
[root@node5 ~]# cd nginx-1.19.3
[root@node5 nginx-1.19.3]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src

[root@node5 nginx-1.19.3]# pwd
/root/nginx-1.19.3

#清除上次的make命令所产生的object和Makefile文件。使用场景:当需要重新执行configure时,需要执行make clean
[root@node5 nginx-1.19.3]# make clean
rm -rf Makefile objs

#检查编译环境,
[root@node5 nginx-1.19.3]# ./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre --add-module=/root/ngx_http_google_filter_module --add-module=/root/ngx_http_substitutions_filter_module

#输出为0,说明上一步成功
[root@node5 nginx-1.19.3]# echo $?
0

#编译
[root@node5 nginx-1.19.3]# make -j 4
#输出为0,说明上一步成功
[root@node5 nginx-1.19.3]# echo $?
0

#备份原有nginx可执行文件
[root@node5 nginx-1.19.3]# mv /usr/local/nginx/sbin/nginx{,`date +%F-%T`}

[root@node5 nginx-1.19.3]# ll objs/nginx 
-rwxr-xr-x 1 root root 6370448 Oct 30 16:55 objs/nginx
#使用新的nginx可执行文件
[root@node5 nginx-1.19.3]# cp objs/nginx /usr/local/nginx/sbin/

#nginx -t查看配置文件是否正确
[root@node5 nginx-1.19.3]# /usr/local/nginx/sbin/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
 
#查看nginx的版本号和详细编译参数,由输出可知,新模块已经添加进去了
[root@node5 nginx-1.19.3]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.19.3
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 --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre --add-module=/root/ngx_http_google_filter_module --add-module=/root/ngx_http_substitutions_filter_module

[root@node5 nginx-1.19.3]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

[root@node5 nginx-1.19.3]# ps -ef | grep nginx
root      36630      1  0 17:03 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     36631  36630  0 17:03 ?        00:00:00 nginx: worker process
nginx     36632  36630  0 17:03 ?        00:00:00 nginx: worker process
root      36641  27402  0 17:03 pts/2    00:00:00 grep --color=auto nginx

#curl nginx端口,输入如下说明nginx功能正常
[root@node5 nginx-1.19.3]# curl http://localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

参考链接:

https://www.cnblogs.com/stulzq/p/9291223.html

https://www.jiangexing.cn/355.html

https://blog.csdn.net/lxw1844912514/article/details/104738967/

https://www.linuxidc.com/Linux/2017-02/140495.htm

https://www.linuxidc.com/Linux/2013-09/89656.htm

posted @ 2020-11-10 16:38  人生的哲理  阅读(1882)  评论(1编辑  收藏  举报