• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
悬溺
博客园    首页    新随笔    联系   管理    订阅  订阅
nginx

nginx

1.nginx平滑升级并添加新功能

源码升级软件或添加功能模块的步骤:

1.准备升级包或功能包

2.获取升级前版本的编译参数

3.解压新版本,使用configure进行配置,配置时加上升级前版本的编译参数,然后添加新功能模块

4.编译(禁止执行make install安装)

5.将老程序停止并使用新程序和老配置文件启动新版本

6.如果第5步成功,并能够正常访问,则备份老版本的程序并同时复制新版本程序覆盖老版本并重启

7.验证

//下载软件包和功能包
[root@localhost ~]# yum -y install git
[root@localhost ~]# wget https://nginx.org/download/nginx-1.23.1.tar.gz
--2022-09-04 10:27:19--  https://nginx.org/download/nginx-1.23.1.tar.gz
Resolving nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
Connecting to nginx.org (nginx.org)|3.125.197.172|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1104352 (1.1M) [application/octet-stream]
Saving to: ‘nginx-1.23.1.tar.gz’

nginx-1.23.1.tar.gz      100%[=================================>]   1.05M  68.8KB/s    in 14s     

2022-09-04 10:27:35 (78.9 KB/s) - ‘nginx-1.23.1.tar.gz’ saved [1104352/1104352]

[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 | 644.00 KiB/s, done.
Resolving deltas: 100% (1635/1635), done.
 //解压软件包
[root@localhost ~]# tar xf nginx-1.23.1.tar.gz 
[root@localhost ~]# ls
anaconda-ks.cfg  echo-nginx-module  nginx-1.23.1  nginx-1.23.1.tar.gz
//备份
[root@localhost ~]# cd /usr/local/nginx/sbin/
[root@localhost sbin]# ls
nginx
[root@localhost sbin]# cp /usr/local/nginx/sbin/nginx{,.bak}
[root@localhost sbin]# ls
nginx  nginx.bak
//编译
[root@localhost nginx-1.23.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
[root@localhost nginx-1.23.1]# make
//编译完看objs里面有nginx主程序
[root@localhost nginx-1.23.1]# cd objs/      
[root@localhost objs]# ls
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src

//查看新版本
[root@localhost ~]# ./nginx-1.23.1/objs/nginx -V
nginx version: nginx/1.23.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-10) (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 ~]# nginx -V
nginx version: nginx/1.20.2
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-10) (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 ~]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     Process     
LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*                    
LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*                    
LISTEN      0           128                       [::]:22                     [::]:*                    
[root@localhost ~]# 
[root@localhost ~]# nginx -s stop    
[root@localhost ~]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     Process     
LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*                    
LISTEN      0           128                       [::]:22                     [::]:*            
    
//测试新版本
[root@localhost nginx-1.23.1]# ./objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.23.1]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     Process     
LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*                    
LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*                    
LISTEN      0           128                       [::]:22                     [::]:*                    
[root@localhost nginx-1.23.1]# ./objs/nginx -s stop -c /usr/local/nginx/conf/nginx.conf
[root@localhost nginx-1.23.1]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     Process     
LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*                    
LISTEN      0           128                       [::]:22                     [::]:*   
[root@localhost nginx-1.23.1]# cp objs/nginx /usr/local/nginx/sbin/
cp: overwrite '/usr/local/nginx/sbin/nginx'? y
cp: cannot create regular file '/usr/local/nginx/sbin/nginx': Text file busy
[root@localhost nginx-1.23.1]# cd /usr/local/nginx/sbin/
//nginx为新版本,bak后缀的为老版本
[root@localhost sbin]# ls
nginx  nginx.bak

[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# cat nginx.conf
server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            echo "hehe";        //添加echo功能
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

//-t验证语法
[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
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@localhost conf]# nginx -s reload     
[root@localhost conf]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     Process     
LISTEN      0           128                    0.0.0.0:80                  0.0.0.0:*                    
LISTEN      0           128                    0.0.0.0:22                  0.0.0.0:*                    
LISTEN      0           128                       [::]:22                     [::]:*     //查看               
[root@localhost conf]# curl 192.168.78.144       
hehe

2.loaction的使用

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

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能
//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

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

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

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

//如没添加任何修饰符则按先后顺序
[root@localhost conf]# vim nginx.conf
//添加三个访问页面测试
location / {
            echo 'haha';
        }

        location /xixi {
            echo 'xixi';
        }

        location /hehe {
            echo 'hehe';
        }
[root@localhost conf]# systemctl restart nginx.service 
[root@localhost conf]# curl 192.168.78.144   
haha
[root@localhost conf]# curl 192.168.78.144/xixi  
xixi
[root@localhost conf]# curl 192.168.78.144/hehe
hehe  
// =精确匹配
[root@localhost conf]# vim nginx.conf
location / {
            echo 'haha;
        }

        location /xixi {
            echo 'xixi';
        }

        location = /xixi {   
            echo 'hehe';
        }

[root@localhost conf]# systemctl restart nginx.service 
//可以看到两个目录一样,但是=优先级大于没有加=的,所以访问的是hehe
[root@localhost conf]# curl 192.168.78.144/xixi   
hehe

//添加 ~ 为区分大小写
[root@localhost conf]# vim nginx.conf
location / {
            echo 'haha';
        }

        location /xixi {
            echo 'xixi';
        }

        location ~ /xixi {   
            echo 'hehe';
        }
[root@localhost conf]# systemctl restart nginx.service 
//因为区分大小写找不到资源所以输出的是默认haha
[root@localhost conf]# curl 192.168.78.144/XIXI
haha
[root@localhost conf]# curl 192.168.78.144/xixi  
hehe

//  ~* 为不区分大小写
[root@localhost conf]# vim nginx.conf
location / {
            echo 'haha';
        }

        location /xixi {
            echo 'xixi';
        }

        location ~* /xixi {
            echo 'hehe';
        }
[root@localhost conf]# systemctl restart nginx.service     
//因为不区分大小写所以XIXI和xixi都能访问到hehe
[root@localhost conf]# curl 192.168.78.144/XIXI
hehe
[root@localhost conf]# curl 192.168.78.144/xixi
hehe


// ^~ 为前缀匹配
[root@localhost conf]# vim nginx.conf
location / {
            echo 'haha';
        }

        location ^~/xixi {   
            echo 'xixi';
        }

        location ~ /xixi {
            echo 'hehe';

[root@localhost conf]# systemctl restart nginx.service 
 //前缀匹配如果访问到了资源则停止搜索
[root@localhost conf]# curl 192.168.78.144/xixi   
xixi

3.访问控制

用于location段

allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开

deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开

//测试
[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html  index.html
[root@localhost html]# echo 'hehe' > index.html 
[root@localhost html]# systemctl restart nginx.service
//虚拟机访问
[root@localhost html]# curl 192.168.78.144
hehe

真机访问

//修改配置文件
[root@localhost html]# cd
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
#access_log  logs/host.access.log  main;

        location / {
            allow 192.168.78.144;    //只允许虚拟机ip访问,拒绝其他所有
            deny all;
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;
[root@localhost conf]# systemctl restart nginx.service
[root@localhost conf]# curl 192.168.78.144
hehe

真机访问

4.基于用户认证

//安装httpd工具包
[root@localhost conf]# yum install httpd-tools -y
[root@localhost conf]# pwd
/usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
#access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;     //默认页面
         }

        location /xixi {    
             auth_basic "haha";        
             auth_basic_user_file "/usr/local/nginx/conf/.pass";  //密码存放位置
             root html;
             index index.html;
        }
            
 //生成用户密码
[root@localhost conf]# htpasswd -cm /usr/local/nginx/conf/.pass runtime
New password:                      //用户为runtime密码为123456
Re-type new password: 
Adding password for user runtime
[root@localhost conf]# cat .pass      //保存后自动加密
runtime:$apr1$M510zBCO$nvDP8xchHAzNHrAcUAWQF1
[root@localhost conf]# systemctl restart nginx.service

测试:直接访问

访问根下的xixi

5.https配置

证书申请及签署步骤

a) 生成申请请求 b) RA核验c) CA签署 d) 获取证书

生成证书

[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/
cakey.pem

CA生成自签署证书

[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]:TX
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]# mkdir certs newcerts crl
[root@localhost CA]# touch index.txt && echo 01 > serial

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

[root@localhost CA]# cd /usr/local/nginx/conf/ && mkdir ssl && 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]:TX
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 []:

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

[root@localhost 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: Sep  5 04:13:13 2022 GMT
            Not After : Sep  5 04:13:13 2023 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = TX
            organizationalUnitName    = www.example.com
            commonName                = www.example.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                E4:C6:A0:20:C2:D0:FF:1E:9C:17:90:BB:4C:59:27:EE:6B:FB:3F:1E
            X509v3 Authority Key Identifier: 
                keyid:19:8C:BE:D2:21:BA:AB:70:F5:3D:78:3B:45:B6:57:AF:4F:A2:3A:0F

Certificate is to be certified until Sep  5 04:13:13 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

配置nginx.conf文件加入生成的密钥和证书

[root@localhost ~]# cd /usr/local/nginx/conf/
//取消注释,加入生成的密钥和证书路径
[root@localhost conf]# vim 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 conf]# systemctl restart nginx.service
[root@localhost conf]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port           Peer Address:Port     Process     
LISTEN      0           128                    0.0.0.0:80                  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                       [::]:22                     [::]:*            

网页查看

继续访问

6.rewrite

//语法:rewrite regex replacement flag;,如:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

//此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

常见的flag

flag 作用
last 基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个 一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理 而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break 中止Rewrite,不再继续匹配 一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求, 且不再会被当前location内的任何rewrite规则所检查
redirect 以临时重定向的HTTP状态302返回新的URL
permanent 以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:

标识符 意义
^ 必须以^后的实体开头
$ 必须以$前的实体结尾
. 匹配任意字符
[] 匹配指定字符集内的任意字符
[^] 匹配任何不包括在指定字符集内的任意字符串
| 匹配 | 之前或之后的实体
() 分组,组成一组用于匹配的实体,通常会有 | 来协助

[root@localhost conf]# vim nginx.conf
#charset koi8-r;

        #access_log  logs/host.access.log  main;

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

        location /images {    
             root html;
        }

        #error_page  404              /404.html;

//创建images图片存放目录
[root@localhost html]# mkdir images
[root@localhost html]# ls
50x.html  images  index.html
[root@localhost html]# cd images/
 //上传一张图片
[root@localhost images]# ls
1628485222577.jpg
[root@localhost images]# mv 1628485222577.jpg 1.jpg
[root@localhost images]# ls
1.jpg

网页测试

//修改名字
[root@localhost html]# mv images imgs
[root@localhost html]# ls
50x.html  imgs  index.html

继续访问之前的网址显示找不到

[root@localhost conf]# vim nginx.conf
server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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

        location /images {
            rewrite ^/images/(.*)$ /imgs/$1 break;     //添加rewrite重定向
        }

        error_page  404              /404.html;
[root@localhost conf]# systemctl restart nginx.service

再访问一遍之前的网站 可以看到图片

7.反向代理与负载均衡

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。

nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了。

但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储。

Http Proxy`模块,功能很多,最常用的是`proxy_pass`和`proxy_cache

如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:
./configure --add-module=../ngx_cache_purge-1.0 ......

nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内

在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如:

upstream idfsoft.com {
  ip_hash;
  server 127.0.0.1:9080 weight=5;
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}

注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,FQ等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。

定义好upstream后,需要在server段内添加如下内容:

server {
  location / {
    proxy_pass http://idfsoft.com;
  }
}
posted on 2022-09-05 13:13  悬溺·  阅读(125)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3