目录

Life in Flow

知不知,尚矣;不知知,病矣。
不知不知,殆矣。

X

Nginx

Nginx1.1.6.0安装

# 下载
[root@localhost software]# wget https://nginx.org/download/nginx-1.16.0.tar.gz

# 依赖
[root@localhost software]# yum install -y pcre pcre-devel openssl openssl-devel gcc gcc-c++ autoconf automake make

# 编译安装步骤
[root@localhost software]# tar xf nginx-1.16.0.tar.gz
[root@localhost software]# cd nginx-1.16.0

[root@localhost nginx-1.16.0]# useradd -s /sbin/nologin www -M
[root@localhost ~]# mkdir /application

[root@localhost nginx-1.16.0]# ./configure --user=www --group=www --prefix=/application/nginx-1.16.0 --with-http_stub_status_module --with-http_ssl_module --with-pcre
[root@localhost nginx-1.16.0]# make
[root@localhost nginx-1.16.0]# make install
[root@localhost nginx-1.16.0]# ln -s /application/nginx-1.16.0/ /application/nginx

# 启动服务
[root@localhost nginx-1.16.0]# /application/nginx/sbin/nginx

# 发现nginx监听在80端口上
[root@localhost nginx-1.16.0]# netstat  -tnlp | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      31813/nginx: master

# 访问nginx
http://192.168.31.212/

目录结构

目录名功能
sbin启动命令
logs日志和进程号对应文件
html默认站点目录
nginx.conf主配置文件
fastcgi.conf动态服务接口配置参数,配合php

命令添加到环境变量中

[root@localhost ~]# echo 'PATH="/application/nginx/sbin:$PATH"' >>/etc/profile
[root@localhost ~]# . /etc/profile
[root@localhost ~]# echo $PATH
/application/nginx/sbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

Nginx常用命令

# 检查配置文件语法是否正确
[root@localhost ~]# nginx -t
nginx: the configuration file /application/nginx-1.16.0/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.16.0/conf/nginx.conf test is successful

# 重新加载配置文件
[root@localhost ~]# nginx -s reload


主配置文件

# 生成没有注解的主配置文件
[root@localhost nginx-1.16.0]# egrep -v "^$|#" /application/nginx/conf/nginx.conf.default  > /application/nginx/conf/nginx.conf

[root@localhost nginx-1.16.0]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

# 删除17行到20行之后的内容
[root@localhost ~]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
    }
}

虚拟主机

基于域名的虚拟主机

[root@localhost ~]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  www.soulboy.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
    }
    server {
        listen       80;
        server_name  www.blog.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
    }

}

[root@localhost ~]# mkdir /application/nginx/html/www
[root@localhost ~]# mkdir /application/nginx/html/blog
[root@localhost ~]# echo "www.soulboy.com" > /application/nginx/html/www/index.html
[root@localhost ~]# echo "www.blog.com" > /application/nginx/html/blog/index.html
[root@localhost ~]# echo "192.168.31.212 www.soulboy.com" >>/etc/hosts
[root@localhost ~]# echo "192.168.31.212 www.blog.com" >>/etc/hosts

# 测试
[root@localhost ~]# curl www.soulboy.com
www.soulboy.com
[root@localhost ~]# curl www.blog.com
www.blog.com

基于端口的虚拟主机

[root@localhost conf]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  www.soulboy.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
    }
    server {
        listen       81;
        server_name  www.blog.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
    }
}

# 测试,如果能解析到ip,但是匹配不到FQDN名,Nginx默认会选择第一个server为请求提供服务
[root@localhost conf]# curl www.blog.com
www.soulboy.com
[root@localhost conf]# curl www.blog.com:81
www.blog.com

基于IP的虚拟主机

# 添加辅助ip
[root@localhost conf]# ip addr add 192.168.31.250/24 dev enp0s3 label enp0s3:10

# 查看配置文件
[root@localhost conf]# cat nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       192.168.31.212:80;
        server_name  www.soulboy.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
    }
    server {
        listen       192.168.31.250:80;
        server_name  www.blog.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
    }
}

# 测试(必须stop,reload没有用)
[root@localhost conf]# nginx -s stop
[root@localhost conf]# nginx
[root@localhost conf]# netstat -tnlp | grep nginx
tcp        0      0 192.168.31.250:80       0.0.0.0:*               LISTEN      19346/nginx: master
tcp        0      0 192.168.31.212:80       0.0.0.0:*               LISTEN      19346/nginx: master
[root@localhost conf]# curl 192.168.31.250
www.blog.com
[root@localhost conf]# curl 192.168.31.212
www.soulboy.com

返回状态码

防止恶意解析,如果解析不到对应的server,则默认走第一个server,返回500

[root@localhost conf]# echo "192.168.31.212 www.oldboy.com" >>/etc/hosts

[root@localhost conf]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server{
        listen 80;
        server_name _default;
        return 500;
    }
    server {
        listen       80;
        server_name  www.soulboy.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
    }
    server {
        listen       80;
        server_name  www.blog.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
    }
}

# 测试
[root@localhost conf]# curl www.soulboy.com
www.soulboy.com
[root@localhost conf]# curl www.blog.com
www.blog.com
[root@localhost conf]# curl www.oldboy.com
<html>
<head><title>500 Internal Server Error</title></head>
<body>
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx/1.16.0</center>
</body>
</html>

配置文件拆分

# 主配置文件
[root@localhost conf]# cat nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
#    include extra/01.soulboy.conf;
#    include extra/02.blog.conf;
    include extra/*.conf;

}


# 01.soulboy.conf
[root@localhost conf]# sed -n '10,17p' nginx.conf >/application/nginx/conf/extra/01.soulboy.conf
[root@localhost conf]# cat extra/01.soulboy.conf
    server {
        listen       80;
        server_name  www.soulboy.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
    }

# 02.blog.conf
[root@localhost conf]# sed -n '18,25p' nginx.conf >/application/nginx/conf/extra/02.blog.conf
[root@localhost conf]# cat extra/02.blog.conf
    server {
        listen       80;
        server_name  www.blog.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
    }

别名

[root@localhost conf]# cat extra/02.blog.conf
    server {
        listen       80;
        server_name  www.blog.com blog.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
    }

[root@localhost conf]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.31.212 www.soulboy.com soulboy.com
192.168.31.212 www.blog.com blog.com
192.168.31.212 www.oldboy.com

[root@localhost conf]# curl blog.com
www.blog.com

Nginx status

# 查看是否安装 status模块
[root@localhost conf]# nginx -V
nginx version: nginx/1.16.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/application/nginx-1.16.0 --with-http_stub_status_module --with-http_ssl_module --with-pcre

# 配置文件
[root@localhost conf]# cat extra/04_status.conf
#status
server{
        listen 80;
        server_name status.soulboy.com;
        location / {
                stub_status on;
                access_log off;
        }
}

# 测试 
## server 表示nginx启动到现在共处理了多少个连接
## accepts 表示nginx启动到现在共成功创建多少次握手
## handle requests 表示总共处理了多少次请求
## Reading 为Nginx读取到客户端的 Header 信息数
## Writing 为Nginx返回给客户端的 Header 信息数
## Waiting 为Nginx已经处理完正在等候下一次请求指令的驻留连接。在开启keep-alive的情况下,这个值等于active-(reading +writing)
[root@localhost conf]# curl status.soulboy.com
Active connections: 1
server accepts handled requests
 12 12 12
Reading: 0 Writing: 1 Waiting: 0

错误日志

[root@localhost conf]# cat nginx.conf
worker_processes  1;
error_log logs/error.log error; #配置错误日志
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
#    include extra/01.soulboy.conf;
#    include extra/02.blog.conf;
    include extra/*.conf;
}

访问日志

# 配置日志格式 main
[root@localhost conf]# cat nginx.conf
worker_processes  1;
error_log logs/error.log error;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

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

#    include extra/01.soulboy.conf;
#    include extra/02.blog.conf;
    include extra/*.conf;


# 在server中开启访问日志,并且引用核心区域的日志格式main
[root@localhost conf]# cat extra/01.soulboy.conf
    server {
        listen       80;
        server_name  www.soulboy.com soulboy.com;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        access_log logs/access_soulboy.log main buffer=32k flush=5s;
    }

# 测试
[root@localhost conf]# curl www.soulboy.com
www.soulboy.com
[root@localhost logs]# cat access_soulboy.log
192.168.31.212 - - [04/May/2021:01:20:21 +0800] "GET / HTTP/1.1" 200 16 "-" "curl/7.29.0" "-"



col1col2
$remote_addr来访者的ip地址
$remote_user来访者用户名
$time_local访问时间、时区
$request用户的http请求起始行信息
$statushttp状态码,记录请求返回的状态:200、404、301等
$body_bytes_sent服务器发送给客户端的响应body字节数
$http_referer记录此次请求是从哪个链接访问过来的,可以根据referer进行防盗链设置
$http_user_agent记录客户端的访问信息:浏览器、手机客户端等
$http_x_forwarded_for当前段有代理服务器时,设置Web节点记录地址的配置,此参数生效的前提是代理服务器上也要进行相关的 x_forwarded_for设置。

访问日志切割

# 编写日志切割脚本 
[root@localhost conf]# cat /software/script/cut_nginx_log.sh
#!/bin/sh
Dateformat=`date +%Y%m%d -d -1day`
Basedir="/application/nginx"
Nginxlogdir="$Basedir/logs"
Logname="access_soulboy"
[ -d $Nginxlogdir ] && cd $Nginxlogdir || exit 1
[ -f ${Logname}.log ] || exit
/bin/mv ${Logname}.log ${Dateformat}_${Logname}.log
$Basedir/sbin/nginx -s reload

# 测试
[root@localhost logs]# sh /software/script/cut_nginx_log.sh
[root@localhost logs]# ls
20210503_access_soulboy.log  access.log  access_soulboy.log  error.log  nginx.pid

# 添加到计划任务,每天凌晨零点执行一次
[root@localhost logs]# crontab -e
#cut log by soulboy at 20210504
00 00 * * * /bin/sh /software/script/cut_nginx_log.sh >/dev/null 2>&1

location

location [= | ~ | ~* | ^ ~ | @] uri {...}

uri是关键,可以是普通的字符串地址路径或者是正则表达式。

~:用于区分大小写的匹配

~*:用于不区分大小写的匹配

!:取反,!~和! ~*

^~:作用是在常规的字符串匹配检查之后,不做正则表达式的检查,即如果最明确的那个字符串匹配的Location配置中有此前缀,那么不做正则表达式的检查。

[root@localhost extra]# cat 01.soulboy.conf
    server {
        listen       80;
        server_name  www.soulboy.com soulboy.com;
        root   html/www;
        location / {
                return 401;
        }
        location = / {
                return 402;
        }
        location /documents/ {
                return 403;
        }
        location ^~ /images/ {
                return 404;
        }
        location ~* \.(gif|jpg|jpeg)$ {
                return 500;
        }
        access_log logs/access_soulboy.log main buffer=32k flush=5s;
    }

# 测试
[root@localhost extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.soulboy.com
402
[root@localhost extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.soulboy.com/
402

[root@localhost extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.soulboy.com/index.html
401

[root@localhost extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.soulboy.com/documents/document.html
403

[root@localhost extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.soulboy.com/images/1.gif404
404

[root@localhost extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.soulboy.com/documents/1.jpg
500

[root@localhost extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.soulboy.com/oldboy/
401

rewrite

[root@localhost extra]# cat 01.soulboy.conf
    server {
        listen 80;
        server_name soulboy.com;
        rewrite ^/(.*)  http://www.soulboy.com/$1 permanent;
    }
    server {
        listen       80;
        server_name  www.soulboy.com;
        root   html/www;
        location / {
                root html/www;
                index index.html index.htm;
        }
        access_log logs/access_soulboy.log main buffer=32k flush=5s;
    }

# 测试
[root@localhost extra]# nginx  -t
nginx: the configuration file /application/nginx-1.16.0/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.16.0/conf/nginx.conf test is successful
[root@localhost extra]# nginx -s reload
[root@localhost extra]# curl -I soulboy.com	# 发现301跳转
HTTP/1.1 301 Moved Permanently
Server: nginx/1.16.0
Date: Mon, 03 May 2021 19:06:08 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.soulboy.com/

[root@localhost extra]# curl -I soulboy.com/oldboy/abc/
HTTP/1.1 301 Moved Permanently
Server: nginx/1.16.0
Date: Mon, 03 May 2021 19:07:44 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.soulboy.com/oldboy/abc/

负载均衡

[root@localhost conf]# cat nginx.conf
worker_processes  1;
error_log logs/error.log error;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    upstream backend {
        server 192.168.31.210:80 weight=1;
        server 192.168.31.211:80 weight=1 max_fails=1 fail_timeout=10s;# 和上面一样,默认就是1,10s
    }

    server {
        listen 80;
        server_name www.soulboy.com;
        location / {
                proxy_pass http://backend;
                proxy_set_header Host $host; # 用户后端的realserver中有多态虚拟主机的时候,根据转发过来的Host 字段判断是哪个虚拟主机。
		proxy_set_header X-Forwarded-For $remote_addr; # realserver 中日志需要配置 "$http_x_forwarded_for" ,可以记录用户的真实IP,否则记录的是负载均衡器的IP
        }
    }

}


作者:Soulboy