nginx配置:

升级版本并添加新功能(平滑升级)

源码升级软件或添加功能模块的步骤:
1.准备升级包或功能包
2.获取升级前版本的编译参数
3.解压新版本,使用conf igure进行配置,配置时加上升级前版本的编译参数,然后添加新功能模块
4.编译(禁止执行make install安装)
5.将老程序停止并使用新程序和老配置文件启动新版本
6.如果第5步成功,并能够正常访问,则备份老版本的程序并同时复制新版本程序覆盖老版本并重启
7.验证

//下载要升级的软件包
[root@localhost ~]# ls
anaconda-ks.cfg  nginx-1.20.2  nginx-1.22.0.tar.gz

准备要升级要用的功能模块,在github.com上找
在这里插入图片描述
在这里插入图片描述

//下载拉包工具
[root@localhost ~]# yum -y install git
[root@localhost ~]# git clone https://github.com/openresty/echo-nginx-module.git
Cloning into 'echo-nginx-module'...
remote: Enumerating objects: 3047, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (20/20), done.
remote: Total 3047 (delta 11), reused 19 (delta 9), pack-reused 3018
Receiving objects: 100% (3047/3047), 1.17 MiB | 771.00 KiB/s, done.
Resolving deltas: 100% (1635/1635), done.
[root@localhost ~]# ls
anaconda-ks.cfg  echo-nginx-module  nginx-1.20.2  nginx-1.22.0.tar.gz
 //复制旧版本的参数
[root@localhost ~]# nginx -V   
nginx version: nginx/1.20.2
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-15) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
[root@localhost ~]# ls
anaconda-ks.cfg  echo-nginx-module  nginx-1.20.2  nginx-1.22.0.tar.gz
[root@localhost ~]# tar -xf nginx-1.22.0.tar.gz 
[root@localhost ~]# ls
anaconda-ks.cfg    nginx-1.20.2  nginx-1.22.0.tar.gz
echo-nginx-module  nginx-1.22.0
[root@localhost ~]# cd nginx-1.22.0/
[root@localhost nginx-1.22.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module    //复制前面的参数,使用前面下载的模块
//省略过程
//编译
//编译(禁止执行make install安装)
[root@localhost nginx-1.22.0]# make
//省略过程
[root@localhost nginx-1.22.0]# ls objs/   //这个目录会生成新版本的主文件,nginx
Makefile      nginx              ngx_auto_headers.h  src
addon         nginx.8            ngx_modules.c
autoconf.err  ngx_auto_config.h  ngx_modules.o
//测试新版本有无问题
[root@localhost nginx-1.22.0]# ./objs/nginx -V    //查看
nginx version: nginx/1.22.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-15) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module
//关闭旧版本nginx,立刻使用新版本测试,减少时间差,确保业务不中断
[root@localhost nginx-1.22.0]# nginx -s stop;./objs/nginx -c /usr/local/nginx/conf/nginx.conf            

[root@localhost nginx-1.22.0]# ss -antl   //开启80
State   Recv-Q  Send-Q   Local Address:Port    Peer Address:Port  Process  
LISTEN  0       128            0.0.0.0:111          0.0.0.0:*              
LISTEN  0       128            0.0.0.0:80           0.0.0.0:*              
LISTEN  0       32       192.168.122.1:53           0.0.0.0:*              

//网页正常访问
在这里插入图片描述

//备份老版本的程序并同时复制新版本程序覆盖老版本并重启
[root@localhost nginx-1.22.0]# mv /usr/local/nginx/sbin/nginx{,.bak};\cp objs/nginx /usr/local/nginx/sbin/;nginx -s stop;nginx   //  \cp不在询问

测试

[root@localhost ~]# nginx -v   //查看版本
nginx version: nginx/1.22.0
[root@localhost ~]# nginx -V
nginx version: nginx/1.22.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-15) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module
[root@localhost conf]# vim nginx.conf     
        location / {
            echo "hehe";      //添加
            root   html;
            index  index.html index.htm;
        }

[root@localhost conf]# nginx.bak -t     //检查语法,老版本有问题
nginx: [emerg] unknown directive "echo" in /usr/local/nginx/conf/nginx.conf:44
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
[root@localhost conf]# nginx -t    //检查语法,新版本ok
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

平滑重启

# 1. 检测修改过后的配置文件是否有错误
	/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
# 2. 平滑重启            //让业务不中断
	/usr/local/nginx/sbin/nginx -s reload
	

location的使用

在这里插入图片描述

location区段,通过指定模式来与客户端请求的URI相匹配

//用curl检测location
[root@localhost conf]# vim nginx.conf
        location /qzl {
            echo 'tt';
        }
[root@localhost conf]# curl 192.168.70.131/qzl
tt
//如果后面的目录没有没有值,以第一个为主
[root@localhost conf]# curl 192.168.70.131/qzl/sdf/sdf
tt   
//没有修饰符表示必须以指定模式开始
[root@localhost conf]# curl 192.168.70.131/qzl/sdf/sdf
tt
[root@localhost conf]# curl 192.168.70.131/qzlasdfjsoidif
tt

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能

//语法:location [ 修饰符 ] pattern {......}
常用修饰符说明:
不用修饰符按顺序执行,有修饰符,按修饰符的优先级执行
//不完整匹配
例:
[root@localhost conf]# vim nginx.conf
        location  ~ /qzl {
            echo 'tt';
        }
[root@localhost conf]# nginx -s reload
[root@localhost conf]# curl 192.168.70.131/qzlsdf
tt
//如果优先级一样,就一直执行先匹配的值,
[root@localhost conf]# vim nginx.conf
        location  ~ /qzl {
            echo 'tt';
        }
        location  ~ /qzli {
            echo 'tts';
        }
[root@localhost conf]# curl 192.168.70.131/qzlsdf
tt
[root@localhost conf]# curl 192.168.70.131/qzlsdf
tt

=:表示必须与指定的模式精确匹配,

[root@localhost conf]# vim nginx.conf
        location = /qzl {
            echo 'tt';
        }
[root@localhost conf]# curl 192.168.70.131/qzl
tt

~:表示指定的正则表达式要区分大小写,如:

        location ~ ^/qzl$ {
            echo 'tt';
        }
[root@localhost conf]# curl 192.168.70.131/qzlasdfj
tt
[root@localhost conf]# curl 192.168.70.131/kqzlasdfj
<html>
<head><title>404 Not Found</title></head>

~*:表示指定的正则表达式不区分大小写

        location ~* ^/qzl$ {
            echo 'tt';
        }

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式

查找顺序和优先级:由高到底依次为

  1. 带有=的精确匹配优先
  2. 正则表达式按照他们在配置文件中定义的顺序
  3. 带有^~修饰符的,开头匹配
  4. 带有*修饰符的,如果正则表达式与URI匹配
  5. 没有修饰符的精确匹配
    优先级次序如下:
( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
示例:

//allow 默认允许所有主机通过
//设置白名单
[root@localhost conf]# vim nginx.conf
        location / {     
            allow 192.168.70.131;
            deny all;
            root   html;
            index  index.html index.htm;
        }
[root@localhost conf]# nginx -s reload
//设置黑名单
        location / {
            deny 192.168.70.131;
            allow all;
            root   html;
            index  index.html index.htm;
        }
//黑白名单都设置,基本不用
        location / {
            deny 192.168.70.131;
            allow 192.169.93.23;
            root   html;
            index  index.html index.htm;
        }


用户认证

        location /hehe {
            auth_basic "tt";    //内容随便
            auth_basic_user_file "/usr/local/nginx/conf/.pass";   //准备生成密钥的位置
            root html;
            index  index.html index.htm;
        }
 //下载软件包
[root@localhost conf]# dnf -y install httpd-tools     

//这里的密码为加密后的密码串,建议用htpasswd来创建此文件:
[root@localhost nginx]# htpasswd -c -m /usr/local/nginx/conf/.pass tom    //tom 网页用户
New password: 
Re-type new password: 
Adding password for user tom

在这里插入图片描述

https配置

实现私有CA

[root@localhost ~]# cd /etc/pki/
[root@localhost pki]# mkdir CA
[root@localhost pki]# cd CA/
[root@localhost CA]# mkdir private
[root@localhost CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.................................................+++++
.......................................................+++++
e is 65537 (0x010001)
[root@localhost CA]# ls
private
[root@localhost CA]# file private/cakey.pem 
private/cakey.pem: PEM RSA private key
[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:runtime
Organizational Unit Name (eg, section) []:www.example.com
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:
[root@localhost CA]# ls
cacert.pem  private
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial
[root@localhost CA]# ls
cacert.pem  certs  crl  index.txt  newcerts  private  serial
[root@localhost CA]# 
[root@localhost nginx]# cd conf/
[root@localhost conf]# mkdir ssl
[root@localhost conf]# cd ssl
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
..........+++++
................................+++++
e is 65537 (0x010001)
[root@localhost ssl]# ls
nginx.key
[root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:runtime
Organizational Unit Name (eg, section) []:www.example.com
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@localhost ssl]# ls
nginx.csr  nginx.key
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Sep  4 19:19:25 2022 GMT
            Not After : Sep  4 19:19:25 2023 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = runtime
            organizationalUnitName    = www.example.com
            commonName                = www.example.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                E3:D6:B8:2F:A7:CB:81:B0:9B:D7:92:4A:B1:F4:38:4F:7D:2F:51:A4
            X509v3 Authority Key Identifier: 
                keyid:59:BC:4B:38:9C:F3:D1:DC:53:CA:10:F8:A8:41:0E:09:85:E8:F8:CD

Certificate is to be certified until Sep  4 19:19:25 2023 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@localhost ssl]# ls
nginx.crt  nginx.csr  nginx.key
[root@localhost ssl]# rm -rf nginx.csr 
[root@localhost ssl]# ls
nginx.crt  nginx.key
[root@localhost ssl]# vim /usr/local/nginx/conf/nginx.conf
[root@localhost ssl]# cat /usr/local/nginx/conf/nginx.conf
//在企业真实情况只需要改下面几行,取消注释,改成这样
    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  www.example.com;  //刚刚配置的域名,

        ssl_certificate      /usr/local/nginx/conf/ssl/nginx.crt; //证书位置,公钥
        ssl_certificate_key  /usr/local/nginx/conf/ssl/nginx.key;   //证书位置,私钥

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }

}
[root@localhost ssl]# nginx -s reload
[root@localhost ssl]# ss -antl
State   Recv-Q  Send-Q   Local Address:Port    Peer Address:Port  Process  
LISTEN  0       128            0.0.0.0:111          0.0.0.0:*              
LISTEN  0       128            0.0.0.0:80           0.0.0.0:*              
LISTEN  0       32       192.168.122.1:53           0.0.0.0:*              
LISTEN  0       128            0.0.0.0:22           0.0.0.0:*              
LISTEN  0       128            0.0.0.0:443          0.0.0.0:* //证书端口             
LISTEN  0       128               [::]:111             [::]:*              
LISTEN  0       128               [::]:22              [::]:*      

在这里插入图片描述

开启状态界面

[root@localhost nginx]# vim conf/nginx.conf   //添加
        location /status {
            stub_status on;
        }

在这里插入图片描述
状态页面信息详解:
在这里插入图片描述

//监控取值的方法
[root@localhost nginx]# curl -s 192.168.70.131/status|awk 'NR==3{print $3}'
16

rewrite重定向

语法:rewrite regex replacement flag;,如:

rewrite ^/images/(.*\.jpg)$ /tj/$1 break;
此处的$1用于引用(.*.jpg)匹配到的内容,又如:

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;
捕获子表达式,可以捕获放在()之间的任何文本,比如:

```java
^(hello|sir)$       //字符串为“hi sir”捕获的结果:$1=hi$2=sir

//这些被捕获的数据,在后面就可以当变量一样使用了
        location /images {
            root html;
        }
[root@192 nginx]# mkdir html/images
[root@192 nginx]# ls
client_body_temp  fastcgi_temp  logs        sbin       uwsgi_temp
conf              html          proxy_temp  scgi_temp
[root@192 nginx]# cd html/images/
[root@192 images]# mv '图片.webp' 1.webp
[root@192 images]# ls
1.webp

在这里插入图片描述

[root@192 html]# mv images/ imgs     //移动图片位置,网页访问不到
[root@192 html]# ls
50x.html  imgs  index.html
[root@192 html]# 
          location /images {
            rewrite ^/images/(.*)$ /imgs/$1 break;    //将之前的改成重定向到imgs,又可用访问到网页了
        }
[root@192 nginx]# vim conf/nginx.conf
//第二种方法
location /images {
            rewrite ^/images/(.*\.jpg)$ https://t7.baidu.com/it/u=2511982910,2454873241&fm=193&f=GIF break;   //将响应换为网页图片的地址
        }   
  



第一次访问images重定向到imgs,在刷新重定向到www.baidu.com

//当前匹配结束 继续匹配下一个
        location /images {
            rewrite ^/images/(.*)$ /imgs/$1 last;
        }
        location /imgs {
            rewrite ^/imgs/(.*)$ http://www.baidu.com break;
        }

在这里插入图片描述
常见的flag
在这里插入图片描述
rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:
在这里插入图片描述
捕获子表达式,可以捕获放在()之间的任何文本,比如:

^(hello|sir)$       //字符串为“hi sir”捕获的结果:$1=hi$2=sir

//这些被捕获的数据,在后面就可以当变量一样使用了

if

语法:if (condition) {…}
应用场景:

server段
location段
常见的condition

变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
正则表达式的模式匹配操作
~:区分大小写的模式匹配检查
~:不区分大小写的模式匹配检查
!和!
:对上面两种测试取反
测试指定路径为文件的可能性(-f,!-f)
测试指定路径为目录的可能性(-d,!-d)
测试文件的存在性(-e,!-e)
检查文件是否有执行权限(-x,!-x)

  • 基于浏览器实现分离案例
if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;              //火狐
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;                  //MSIE依然是使用最广泛的网页浏览器
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;                //Chrome(谷歌浏览器)
}

根据用户client_agent判断转发

这种也是典型的,根据用户七层请求头部信息,基于http的不同值,做转发处理。

需求

1. 如果用户是iphone跳转到iphone页面
2. 如果用户是Android跳转的android页面
3. 如果用户是PC端,跳转到PC页面
4. 如果用户是IE浏览器,提示他该升级电脑了。。。IE已经被世界淘汰了。

配置文件

vim /etc/nginx/conf.d/huya.yuchaoit.conf

# 这里是简单用法,更精确的应该是配置如 m.huya.com这样的移动端虚拟主机
upstream android {
    server 10.0.0.81;
}

upstream pc {
    server 10.0.0.82;
}
server {

    listen 80;
    server_name www.chaoge.cc;

    location / {
        # 默认页面,交给pc
        proxy_pass http://pc;
    # 判断是安卓用户
    if ($http_user_agent ~* "android"){
        proxy_pass http://android;
        }

        # 如果是IE,禁止访问
        if ($http_user_agent ~* "msie"){
                return 403 "禁止访问!!IE被淘汰了都。。抓紧升级吧老哥\n";
                }


重载nginx

nginx -s reload

防盗链案例

//从首页跳转进来的为正常
location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;     //端口填主页端口
  if ($invalid_referer) {            //如果是从别的网站跳转过来的,说明有问题,则把他随便丢到一个网站
    rewrite ^/ http://www.idfsoft.com/403.html;       //或者搞个没有的网站
  }
}

nginx负载均衡

默认rr轮训

//配置负载均衡
[root@nginx nginx]# vim conf/nginx.conf
    upstream backend {         
        server 192.168.70.139;  //RS的IP
        server 192.168.70.131;  //RS的IP
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://backend;   //名字与上面一样
        }
 [root@nginx nginx]# nginx -s reload

在这里插入图片描述
在这里插入图片描述

weight权重实践

按比例分配

upstream  web-pools {
    server 172.16.1.7:8080 weight=2;
    server 172.16.1.8:8080 weight=8;
}

ip_hash实践

这个方法确保了相同的客户端的请求一直发送到相同的服务器,这样每个访客都固定访问一个后端服务器。如用户需要分片上传文件到服务器下,然后再由服务器将分片合并,这时如果用户的请求到达了不同的服务器,那么分片将存储于不同的服务器目录中,导致无法将分片合并,该场景则需要使用ip hash策略。
需要注意的是,ip_hash不能与backup同时使用,另外当有服务器需要剔除,必须手动down掉,此模式适合有状态服务,比如session。

ip_hash类似,该算法根据客户端请求的URL信息进行hash得到唯一值,让每个URL固定的发给同一个后端服务器,后端服务器为缓存服务器效果最佳。

Nginx本身是不支持url_hash的,需要单独安装hash模块
url_hash(web缓存节点)和ip_hash(会话保持)功能类似。

upstream  web-pools {
    ip_hash;
    server 172.16.1.7:8080 ; 
    server 172.16.1.8:8080 ; 
}

直接添加ip_hash关键字即可,后续同一ip的访问将只会请求同一个服务器。

注意事项
一旦使用了ip_hash,当我们需要移除一台服务器的时候,不能直接删除这个配置项,而是需要在这台服务器配置后面加上关键字down,表示不可用;
因为如果直接移除配置项,会导致hash算法发生更改,后续所有的请求都会发生混乱;

最少连接

轮询算法是把请求平均的转发给各个后端,使它们的负载大致相同;但是,有些请求占用的时间很长,会导致其所在的后端负载较高。这种情况下,least_conn这种方式就可以达到更好的负载均衡效果,适合请求处理时间长短不一造成服务器过载的情况。

定义转发分配规则

upstream myapp1 {
	least_conn; # 把请求分派给连接数最少的服务器
	server srv1.com;
	server srv2.com:8088;
	server 192.168.0.100:8088;
}

转载部分文章:
原文:更多查看http://t.csdn.cn/TkR2L

单个虚拟主机,记录日志

针对每一个网站,单独的记录日志文件,便于分类管理。
正确的日志使用姿势如下。

如果你觉得,默认的日志,和单独指定的日志,太混乱,
1.你就这么做,每一个虚拟主机,单独的设置日志参数,就行了,不需要去关心那个默认的日志(记录一堆网站的请求,也没什么实际意义)
只有针对单个的网站业务,记录的日志,才有提取,分析的意义。

在这里插入图片描述

语法就是,将日志格式的配置参数,别写在http{}花括号中,而是写在各自的server{}虚拟主机中即可。
# 语法要求,log_format 格式化的日志的名字,还不得重复, lol.linux0224.conf里面的main改为main2


1.去掉nginx.conf中的日志配置
# http{}区域中 nginx.conf中什么也别写了
# log_format参数依然得写在http{}区域中 ,可以利用include语法实现
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    #gzip  on;
    include /etc/nginx/conf.d/*.conf;    //包含了配置文件
}

2.针对每一个虚拟主机,添加日志格式参数,主要的是,分别写入到不同的日志文件中
[root@web-8 /etc/nginx/conf.d]#cat dnf.linux0224.conf 
# 这个参数和server{}平级

 log_format  main  '$document_uri  $remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
server {
	# 开启日志功能,以及存放路径,参数写在server{}内
    access_log  /var/log/nginx/dnf.linux0224.cc.access.log  main;  //用域名辨别,更好区分
    listen 80;
    server_name dnf.linux0224.cc; # 这里写的是域名
	charset utf-8;
    location /  {
        root  /www/dnf/;
        index  index.html;
    }

}


3. 单独记录lol域名业务的访客日志
[root@web-8 /etc/nginx/conf.d]#cat lol.linux0224.conf 

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

server {
    access_log  /var/log/nginx/lol.linux0224.cc.access.log  main2;
    listen 80;
    server_name lol.linux0224.cc;
	charset utf-8;
    location /  {
        root  /www/lol/;
        index  index.html;
    }

}



4.注意,开启access_log日志的参数,可以写在server{}区域里,但是日志格式化的参数,只能写在http{}区域中


测试不同虚拟主机的日志记录

现在有2个虚拟主机,单独记录了日志,

dnf页面的访问情况,与日志记录
在这里插入图片描述

nginx提供的日志

记录用户访问记录的 ,access_log

记录nginx运行错误的日志  error_log

关于该参数的官网文档,以及具体的用法
https://nginx.org/en/docs/ngx_core_module.html#error_log

和access_log用法一样去以及
http{}
server{} 区域里面

Syntax:	error_log file [level];
Default:	
error_log logs/error.log error;
Context:	main, http, mail, stream, server, location


具体的level是指,日志记录的详细程度
有这些值让你填写
debug, info, notice, warn, error, crit, alert

从左到右,详细程度分别是 从 大  >>> 小

debug 会记录超级详细的信息,没必要,占用大量的磁盘空间
crit 表示nginx以及出现严重错误,以及崩溃了,才记录日志。。记录的内容太少
一般用的,以及默认的就是error日志级别,能够记录基本的,常见错误。

错误日志
1. 如何开启error级别的错误日志。
# 单独给的lol虚拟主机网址,设置错误日志,eroor级别 ,配置如下
# 支持写入http{}  server{}
[root@web-8 /etc/nginx/conf.d]#cat  lol.linux0224.conf 

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

server {
    access_log  /var/log/nginx/lol.linux0224.cc.access.log  main2;
    error_log /var/log/nginx/lol-error.log error;

    listen 80;
    server_name lol.linux0224.cc;
	charset utf-8;
    location /  {
        root  /www/lol/;
        index  index.html;
    }

}

重启服务
[root@web-8 /etc/nginx/conf.d]#systemctl restart nginx

检查日志
[root@web-8 /etc/nginx/conf.d]#tail -f /var/log/nginx/lol-error.log 

错误日志的,特点是记录,访问时的出错信息




2. 如何单独给作业2的每一个虚拟主机设置错误日志。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值