Nginx 配置文件详解②

错误页面配置

error_page code(状态码) [...] [=code] URI | @name 根据http响应状态码来指明特用的错误页面,例如 error_page 404 /404_customed.html //如果访问的网页返回404转态码,就使用404_customed.html这个网页响应

访问正常的情况下返回的转态码是200
在这里插入图片描述
下面我们访问一个不存在URI(统一资源标识符),出现了404状态码服务器没有找到要请求的资源,因为我们没有sadfs这个资源
在这里插入图片描述
如果想要实现 网页出现404转态码时,就使用404_customed.html这个网页响应就要修改配置文件

[root@nginx conf]# pwd
/usr/local/nginx/conf
[root@nginx conf]# vim nginx.conf
......
//这里的/根并不是系统的/,而是安装目录中/nginx/html目录
error_page  404              /404.html;   
......

//此时我们去配置一个404.html的页面
[root@nginx nginx]# cd html/
[root@nginx html]# ls
50x.html  index.html
[root@nginx html]# vim 404.html
[root@nginx html]# cat 404.html 
'服务器出现404客户端错误,请注意查看资源路径后,重试!!!'

//重新加载配置文件然后刷新页面内容
[root@nginx html]# nginx -s reload

这里出现了乱码是因为没有使用标准的格式编写内容,但是效果是出来了。其实可以在网上找一个公益不盈利的网页,进行下载 然后把下载页面文件放到html目录中也是可以的,见第二张图
在这里插入图片描述
图2

[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如`` error_page 404 =200 /404_customed.html 也是说如果访问页面出现404状态码时就由404_customed.html提供页面并且将转态码改成200

[root@nginx conf]# pwd
/usr/local/nginx/conf
[root@nginx conf]# vim nginx.conf
......
//这里的/根并不是系统的/,而是安装目录中/nginx/html目录
error_page  404 =200             /404.html;   
......
[root@nginx conf]# nginx -s reload  //重新加载配置文件

此时转态码已经改成200了
在这里插入图片描述

log_format定义日志格式
$remote_addr :访问这个地址的客户IP
“-”就是-
$ remote_user : 远程用户,用哪个用户远程访问的这个网页,这里没有用户所以用“-”来代替
$time_local: 本地时间
$request : 请求,用什么方式请求的,用的http什么版本
$status : 状态码 300表示重定向,是从缓存中提取数据给客户端的。
$body_bytes_sent : 请求的字节0
$http_referer : 是否跳转访问 - 就是否,就是直接输入网址,不是在主页中点击进入的。
h t t p u s e r a g e n t : 用 户 代 理 , 也 就 是 浏 览 器 信 息 “ − ” 最 后 一 个 − 表 示 从 哪 跳 过 来 的 , 因 为 前 面 的 http_user_agent : 用户代理,也就是浏览器信息 “-”最后一个-表示从哪跳过来的,因为前面的 httpuseragenthttp_referer是否,所有这里也没有内容

//打开错误日志功能
[root@nginx conf]# vim nginx.conf
......
//开启错误日志
error_log  logs/error.log;  
 
//访问页面的错误日志格式
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;   //错误日志存放的位置
......
[root@nginx conf]# nginx -s reload  //重新加载配置文件

//重新访问Nginx主页,然后查看日志文件内容。这里的内容就是和配置文件中的变量一一对应的。
[root@nginx logs]# tail access.log 
192.168.164.1 - - [27/Oct/2021:21:26:44 +0800] "GET /sadfs HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30" "-"


平滑升级和echo功能

一种用户无法感知升级过程的一种升级方式

要实现平滑升级要先下载一个一块,到Gitup中下载 https://github.com/openresty/echo-nginx-module

[root@nginx ~]# ls
anaconda-ks.cfg  echo-nginx-module-master.zip

平滑升级: 不能执行安装操作
1、获取老版本的编译参数 -V
2、获取新版本或新功能的软件包
3、新功能或新版本的软件包进行编译,不执行安装
4、备份老程序
5、停掉老程序,并用新程序和老程序的配置文件组合启动
6、检验功能,若无问题就用新程序替换老程序,若有问题就停掉新程序启动老程序

//1、获取老版本的编译参数
[root@nginx ~]# nginx -V
nginx version: nginx/1.12.1
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: --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

//2、获取新版本或新功能的软件包,刚刚已经下载过了
[root@nginx src]# ls
debug                         kernels
echo-nginx-module-master.zip  nginx-1.12.1.tar.gz

//3、新功能或新版本的软件包进行编译,不执行安装
# 解压,如果没有命令需要yum安装一个unzip
[root@nginx src]# unzip echo-nginx-module-master.zip
[root@nginx src]# tar xf nginx-1.12.1.tar.gz
[root@nginx src]# ls
debug                         kernels
echo-nginx-module-master      nginx-1.12.1
echo-nginx-module-master.zip  nginx-1.12.1.tar.gz

# 老版本的编译参数加上新的模块的位置进行安装配置,然后编译
[root@nginx nginx-1.12.1]# ./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-master

# 编译,但是不能安装!!!
[root@nginx nginx-1.12.1]# make

# 编译完成后在obj里面就有了Nginx的主程序
[root@nginx nginx-1.12.1]# ls objs/
addon         nginx              ngx_auto_headers.h  src
autoconf.err  nginx.8            ngx_modules.c
Makefile      ngx_auto_config.h  ngx_modules.o

# 新安装的Nginx加了新功能所有要比老的版本大很多
[root@nginx nginx-1.12.1]# ll objs/nginx  /usr/local/nginx/sbin/nginx 
-rwxr-xr-x. 1 root root 6669928 1027 22:32 objs/nginx
-rwxr-xr-x. 1 root root 6058160 1026 10:37 /usr/local/nginx/sbin/nginx

//4、备份老程序,把老程序复制一份到opt中
/sbin/nginx
[root@nginx nginx-1.12.1]# cp /usr/local/nginx/sbin/nginx  /opt/
[root@nginx nginx-1.12.1]# ls /opt/
nginx


//5、停掉老程序,并用新程序和老程序的配置文件组合启动
[root@nginx nginx-1.12.1]# nginx -s stop;objs/nginx -c /usr/local/nginx/conf/nginx.conf
# 停掉老程序,启动新程序时,指定用老程序的配置文件

# 使用的新程序,用的老配置文件
[root@nginx nginx-1.12.1]# ps -ef | grep nginx
root      98846      1  0 22:39 ?        00:00:00 nginx: master process objs/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     98847  98846  0 22:39 ?        00:00:00 nginx: worker process
root      99197   1452  0 22:39 pts/0    00:00:00 grep --color=auto nginx

# 修改配置文件
[root@nginx ~]# vim  /usr/local/nginx/conf/nginx.conf
......
location /abc {
          echo "hello";
}
......
# 检查一下使用新版本老配置文件 语法是否有问题
[root@nginx nginx-1.12.1]# objs/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

# 程序加载配置文件
[root@nginx nginx-1.12.1]# objs/nginx  -s reload

//6、命令行检验功能,若无问题就用新程序替换老程序,若有问题就停掉新程序启动老程序
C:\Users\>curl http://192.168.164.128/abc
hello   //能打印hello,说明uri匹配到了/abc
C:\Users\>

# 新程序替换老程序
[root@nginx nginx-1.12.1]# \cp objs/nginx /usr/local/nginx/sbin/  //新程序覆盖老程序
[root@nginx nginx-1.12.1]# ll objs/nginx /usr/local/nginx/sbin/nginx   //查看两个地方的程序是否一样大,一样大表示替换成功
-rwxr-xr-x. 1 root root 6669928 1027 22:32 objs/nginx
-rwxr-xr-x. 1 root root 6669928 1027 22:51 /usr/local/nginx/sbin/nginx

# 此时就可以直接使用默认方式 Nginx启动,不用在使用objs/nginx 方式启动
[root@nginx nginx-1.12.1]# objs/nginx -s stop;nginx
[root@nginx nginx-1.12.1]# ps -ef | grep nginx   //此时使用的就是新的程序
root       4518      1  0 22:55 ?        00:00:00 nginx: master process nginx
nginx      4519   4518  0 22:55 ?        00:00:00 nginx: worker process
root       5013   1452  0 22:55 pts/0    00:00:00 grep --color=auto nginx

location配置

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

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

//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

修饰符功能
=精确匹配
~正则表达式模式匹配,区分大小写
~*正则表达式模式匹配,不区分大小写
^~前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

如果没有匹配到相应的内容则用默认的主页响应http://xxx.com/

没有修饰符表示必须以指定模式开始,如:

[root@nginx conf]# vim nginx.conf
......
server {
  server_name www.idfsoft.com;
  location /abc {
    ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22 //“?” 向服务器提交数据 账户密码这类的验证
  • http://www.idfsoft.com/abc/

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

server {
  server_name www.idfsoft.com;
  location = /abc {
    ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22

如下内容则无法匹配:

  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abc/abcde

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

server {
  server_name www.idfsoft.com;
  location ~ ^/abc$ {
  ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22

如下内容则无法匹配:

  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/ABC
  • http://www.idfsoft.com/abcde

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

server {
  server_name www.idfsoft.com;
  location ~* ^/abc$ {
    ......
  }
}

那么如下内容就可正确匹配:

  • http://www.idfsoft.com/abc
  • http://www.idfsoft.com/abc?p1=11&p2=22
  • http://www.idfsoft.com/ABC

如下内容则无法匹配:

  • http://www.idfsoft.com/abc/
  • http://www.idfsoft.com/abcde
    ~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式

官方文档实例:

[root@nginx conf]# vim nginx.conf
#access_log  logs/host.access.log  main;

        location = / {
          echo  "[ configuration A ]";
        }

        location / {
          echo  "[ configuration B ]";
        }

        location /documents/ {
          echo  "[ configuration C ]";
        }

        location ^~ /images/ {
          echo  "[ configuration D ]";
        }

        location ~* \.(gif|jpg|jpeg)$ {
           echo  "[ configuration E ]";
        }


        error_page  404 =200             /404.html;

在这里插入图片描述
1、= 是精确匹配所有可以匹配到主页面
2、“location / {” 所有匹配都没有匹配到,所以就使用的默认主页来响应
3、“location /documents/” 匹配到了documents目录下的文件
4、“ location ^~ /images/” 同样可以匹配到,这个是以/images 开头的
5、最后一个匹配到的是E 因为第3个是没修饰符的优先级最低,且最后一个指定的$ 结尾,说以匹配到了E

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

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

如果有=不关在上面还是下面都最先匹配,其次是正则表达式的位置,先匹配上面的正则再匹配下面的正则,所有我们一般都是把范围小的放到上面比如区分大小写的放在上面。

优先级次序如下:

( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

访问控制

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

location /test {
            allow 192.168.164.1;   //添加允许的访问IP
            allow 192.168.165.1;    //添加允许的网段
            deny all;    //禁止所有人访问,除了上面两个IP
            root   html;
            index  index.html;
        }

这样就只有164.1和165.1地址的主机访问,其他所有主机都不行

用户认证

官方用户认证模块详解

语法、使用位置

Syntax: 	auth_basic string | off;  语法
Default: 	auth_basic off;   //默认关闭
Context: 	http, server, location, limit_except   //使用位置

user_auth_file内容格式为:

username:password

这里的密码为加密后的密码串,建议用htpasswd来创建此文件:

htpasswd -c -m /path/to/.user_auth_file USERNAME

基于用户认证测试

密码放置位置

//使用htpasswd命令生成密码,若没有htpasswd命令。yum安装httpd-tools包即可
[root@nginx conf]# htpasswd -c -m .pass admin
New password: 
Re-type new password: 
Adding password for user admin
[root@nginx conf]# cat .pass 
admin:$apr1$vPWj84D5$vmhK9FW3zl3mEAa/VkRNL0    //生成的密码以加密的方式存放

修改配置文件

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
        location /test {
            auth_basic "欢迎光临";     
            auth_basic_user_file ".pass";      //因为密码文件和配置文件同级目录,所以可以直接写相对路径
            root   html;
            index  index.html;
        }
......
[root@nginx ~]# nginx -s reload   //重新加载配置文件

https配置

创建密钥放置位置

//放置在/conf下
[root@nginx conf]# mkdir ssl 

生成私钥

[root@nginx ~]# mkdir /etc/pki/CA
[root@nginx ~]# cd /etc/pki/CA/
[root@nginx CA]# mkdir private && (umask 077;openssl genrsa -out private/cakey.pem 2048)     //生成密钥,括号必须要
Generating RSA private key, 2048 bit long modulus (2 primes)
.................+++++
........................................................+++++
e is 65537 (0x010001)

CA生成自签署证书

[root@nginx 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]:xx   //组织
Organizational Unit Name (eg, section) []:xxa   //组织单元
Common Name (eg, your name or your server's hostname) []:test.wwww.com    //域名
Email Address []:1@2.com     //邮箱

[root@nginx CA]# mkdir certs newcerts crl
[root@nginx CA]# touch index.txt && echo 01 > serial

[root@nginx CA]# ls 
cacert.pem  crl        newcerts  privite
certs       index.txt  private   serial

客户端(例如httpd服务器)生成密钥

[root@nginx ~]# cd /usr/local/nginx/conf/ssl/
[root@nginx ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.....+++++
.....+++++
e is 65537 (0x010001)
[root@nginx ssl]# ls 
nginx.key

客户端生成证书签署请求

[root@nginx ssl]# pwd
/usr/local/nginx/conf/ssl
[root@nginx 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]:xx   //这里生成的信息一定要和CA自签证书生成信息一样
Organizational Unit Name (eg, section) []:xxa    
Common Name (eg, your name or your server's hostname) []:test.wwww.com
Email Address []:1@2.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:     //回车
An optional company name []:      //回车

[root@nginx ssl]# ll 
total 8
-rw-r--r-- 1 root root 1013 Oct 28 00:01 nginx.csr
-rw------- 1 root root 1679 Oct 27 23:57 nginx.key

客户端把证书签署请求文件发送给CA
此步骤略过,因为此次实验室是在一台机器上操作的,所有无需发送

CA签署客户端提交上来的证书

[root@nginx ssl]# pwd 
/usr/local/nginx/conf/ssl
[root@nginx ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using 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: Oct 27 21:05:44 2021 GMT
            Not After : Oct 27 21:05:44 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = xx
            organizationalUnitName    = xxa
            commonName                = test.wwww.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                94:56:67:E6:F9:40:DD:62:86:33:28:44:F4:D8:F8:40:86:53:9A:8F
            X509v3 Authority Key Identifier: 
                keyid:3B:43:3D:DE:D7:F9:EF:9B:BE:A8:4A:B2:6D:AA:22:2F:2D:C9:FD:A0

Certificate is to be certified until Oct 27 16:05:45 2022 GMT (365 days)
Sign the certificate? [y/n]:y    //y


1 out of 1 certificate requests certified, commit? [y/n]y  //y
Write out database with 1 new entries
Data Base Updated

[root@nginx ssl]# ll
total 16
-rw-r--r-- 1 root root 4503 Oct 28 00:05 nginx.crt
-rw-r--r-- 1 root root 1013 Oct 28 00:01 nginx.csr
-rw------- 1 root root 1679 Oct 27 23:57 nginx.key

[root@nginx ssl]# rm -rf nginx.csr   //生成过后就不需要这个文件了 删除即可

CA把签署好的证书httpd.crt发给客户端
此步骤略过,因为此次实验是在一台机器上操作的,所以无需发送

修改配置文件

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
......
把此部分所有注释去掉
    
    server {
        listen       443 ssl;
        server_name  test.wwww.com;     //改为申请证书时的域名

        ssl_certificate      ssl/nginx.crt;    //修改以下两处
        ssl_certificate_key  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@nginx ~]# nginx -s reload   //重新加载配置文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值