nginx实战

1.nginx简介

1.1 什么是nginx

Nginx 是高性能的 HTTP 和反向代理的web服务器,处理高并发能力是十分强大的,能经受高负 载的考验,有报告表明能支持高达 50,000 个并发连接数。

其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

1.2 Nginx 作为 web 服务器

Nginx 可以作为静态页面的 web 服务器,同时还支持 CGI 协议的动态语言,比如 perl、php 等。但是不支持 java。Java 程序只能通过与 tomcat 配合完成。Nginx 专为性能优化而开发, 性能是其最重要的考量,实现上非常注重效率 ,能经受高负载的考验,有报告表明能支持高 达 50,000 个并发连接数。

https://lnmp.org/nginx.html

1.3 正向代理

Nginx 不仅可以做反向代理,实现负载均衡。还能用作正向代理来进行上网等功能。 正向代理:如果把局域网外的 Internet 想象成一个巨大的资源库,则局域网中的客户端要访 问 Internet,则需要通过代理服务器来访问,这种代理服务就称为正向代理。

简单一点:通过代理服务器来访问服务器的过程 就叫 正向代理。

需要在客户端配置代理服务器进行指定网站访问

1.4 反向代理

反向代理,其实客户端对代理是无感知的,因为客户端不需要任何配置就可以访问。

我们只 需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据后,在返 回给客户端,此时反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器 地址,隐藏了真实服务器 IP 地址。

1.5 负载均衡

增加服务器的数量,然后将请求分发到各个服务器上,将原先请求集中到单个服务器上的 情况改为将请求分发到多个服务器上,将负载分发到不同的服务器,也就是我们所说的负 载均衡

客户端发送多个请求到服务器,服务器处理请求,有一些可能要与数据库进行交互,服 务器处理完毕后,再将结果返回给客户端。

  • 这种架构模式对于早期的系统相对单一,并发请求相对较少的情况下是比较适合的,成 本也低。但是随着信息数量的不断增长,访问量和数据量的飞速增长,以及系统业务的复杂 度增加,这种架构会造成服务器相应客户端的请求日益缓慢,并发量特别大的时候,还容易 造成服务器直接崩溃。很明显这是由于服务器性能的瓶颈造成的问题,那么如何解决这种情 况呢?

  • 我们首先想到的可能是升级服务器的配置,比如提高 CPU 执行频率,加大内存等提高机 器的物理性能来解决此问题,但是我们知道摩尔定律的日益失效,硬件的性能提升已经不能 满足日益提升的需求了。最明显的一个例子,天猫双十一当天,某个热销商品的瞬时访问量 是极其庞大的,那么类似上面的系统架构,将机器都增加到现有的顶级物理配置,都是不能 够满足需求的。那么怎么办呢?上面的分析我们去掉了增加服务器物理配置来解决问题的办法,也就是说纵向解决问题 的办法行不通了,那么横向增加服务器的数量呢?这时候集群的概念产生了,单个服务器解 决不了,我们增加服务器的数量,然后将请求分发到各个服务器上,将原先请求集中到单个服务器上的情况改为将请求分发到多个服务器上,将负载分发到不同的服务器,也就是我们 所说的负载均衡

1.6 动静分离

将静态资源和服务分开,静态资源有js,css,图片等文件,把静态资源和动态资源进行分开,分担服务器的压力,让服务器能更好的发挥性能,提升响应速度。

2.nginx安装

下载官网:http://nginx.org/en/download.html

此处安装的是nginx-1.22.1版本 下载地址: http://nginx.org/download/nginx-1.22.1.tar.gz

sh 复制代码
#安装Nginx依赖环境,-y表示所有提示默认选择y
yum -y install pcre pcre-devel
yum -y install zlib zlib-devel
yum -y install openssl openssl-devel

解压nginx (可以先创建好一个目录,然后把nginx压缩包上传上去,然后进行解压)

sh 复制代码
tar -zxvf nginx-1.22.1.tar.gz # 解压到当前路径
tar -zxvf nginx-1.22.1.tar.gz # 解压到指定路径

编译nginx (进入解压后的nginx目录里面依次执行)

sh 复制代码
./configure --prefix=/web/nginx-install # prefix指定nginx的安装目录
make #编译nginx(生成2进制)
make install # 安装nginx(把生成的 2 进制复制到 prefix 指定的安装路径里)

开发端口号,如果是云服务器,还需要先在云服务器的防火墙规则中开放80端口

sh 复制代码
# 开启 80 端口
firewall-cmd --permanent --zone=public --add-port=80/tcp --permanent

# 查看端口情况,yes即开启成功
firewall-cmd --permanent --query-port=80/tcp

# 重载防火墙
firewall-cmd --reload

# 主机启动时,开启防火墙
systemctl enable firewalld
firewall-cmd --permanent --zone=public --add-port=8005/tcp --permanent

去安装目录的sbin目录下执行 : ./nginx 启动nginx

查看nginx启动情况

sh 复制代码
ps -ef|grep nginx

接下来直接访问域名或ip就可以访问到欢迎页面

nginx相关参数说明:

sh 复制代码
[root@admin sbin]# ./nginx -h
nginx version: nginx/1.22.1
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : 显示nginx版本号
  -V            : 显示版本和配置选项,然后退出
  -t            : 测试配置和退出
  -T            : 测试配置,转储并退出
  -q            : 配置测试时禁止非错误消息
  -s signal     : 向msater进程发送信号: stop, quit, reopen, reload
  -p prefix     : 设置前缀路径(默认:/web/nginx/nginx-install/)
  -e filename   : 设置错误日志文件(默认:logs/error.log)
  -c filename   : 设置配置文件(默认:/web/nginx/nginx-install/conf/nginx.conf)
  -g directives : 设置配置文件(默认:/web/nginx/nginx-install/conf/nginx.conf)从配置文件中设置全局指令

configure 相关参数:

sh 复制代码
 --prefix=PATH                      set installation prefix
  --sbin-path=PATH                   set nginx binary pathname
  --modules-path=PATH                set modules path
  --conf-path=PATH                   set nginx.conf pathname
  --error-log-path=PATH              set error log pathname
  --pid-path=PATH                    set nginx.pid pathname
  --lock-path=PATH                   set nginx.lock pathname

  --user=USER                        set non-privileged user for
                                     worker processes
  --group=GROUP                      set non-privileged group for
                                     worker processes

  --build=NAME                       set build name
  --builddir=DIR                     set build directory

  --with-select_module               enable select module
  --without-select_module            disable select module
  --with-poll_module                 enable poll module
  --without-poll_module              disable poll module

  --with-threads                     enable thread pool support

  --with-file-aio                    enable file AIO support

  --with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
  --with-http_realip_module          enable ngx_http_realip_module
  --with-http_addition_module        enable ngx_http_addition_module
  --with-http_xslt_module            enable ngx_http_xslt_module
  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module
  --with-http_image_filter_module    enable ngx_http_image_filter_module
  --with-http_image_filter_module=dynamic
                                     enable dynamic ngx_http_image_filter_module
  --with-http_geoip_module           enable ngx_http_geoip_module
  --with-http_geoip_module=dynamic   enable dynamic ngx_http_geoip_module
  --with-http_sub_module             enable ngx_http_sub_module
  --with-http_dav_module             enable ngx_http_dav_module
  --with-http_flv_module             enable ngx_http_flv_module
  --with-http_mp4_module             enable ngx_http_mp4_module
  --with-http_gunzip_module          enable ngx_http_gunzip_module
  --with-http_gzip_static_module     enable ngx_http_gzip_static_module
  --with-http_auth_request_module    enable ngx_http_auth_request_module
  --with-http_random_index_module    enable ngx_http_random_index_module
  --with-http_secure_link_module     enable ngx_http_secure_link_module
  --with-http_degradation_module     enable ngx_http_degradation_module
  --with-http_slice_module           enable ngx_http_slice_module
  --with-http_stub_status_module     enable ngx_http_stub_status_module

  --without-http_charset_module      disable ngx_http_charset_module
  --without-http_gzip_module         disable ngx_http_gzip_module
  --without-http_ssi_module          disable ngx_http_ssi_module
  --without-http_userid_module       disable ngx_http_userid_module
  --without-http_access_module       disable ngx_http_access_module
  --without-http_auth_basic_module   disable ngx_http_auth_basic_module
  --without-http_mirror_module       disable ngx_http_mirror_module
  --without-http_autoindex_module    disable ngx_http_autoindex_module
  --without-http_geo_module          disable ngx_http_geo_module
  --without-http_map_module          disable ngx_http_map_module
  --without-http_split_clients_module disable ngx_http_split_clients_module
  --without-http_referer_module      disable ngx_http_referer_module
  --without-http_rewrite_module      disable ngx_http_rewrite_module
  --without-http_proxy_module        disable ngx_http_proxy_module
  --without-http_fastcgi_module      disable ngx_http_fastcgi_module
  --without-http_uwsgi_module        disable ngx_http_uwsgi_module
  --without-http_scgi_module         disable ngx_http_scgi_module
  --without-http_grpc_module         disable ngx_http_grpc_module
  --without-http_memcached_module    disable ngx_http_memcached_module
  --without-http_limit_conn_module   disable ngx_http_limit_conn_module
  --without-http_limit_req_module    disable ngx_http_limit_req_module
  --without-http_empty_gif_module    disable ngx_http_empty_gif_module
  --without-http_browser_module      disable ngx_http_browser_module
  --without-http_upstream_hash_module
                                     disable ngx_http_upstream_hash_module
  --without-http_upstream_ip_hash_module
                                     disable ngx_http_upstream_ip_hash_module
  --without-http_upstream_least_conn_module
                                     disable ngx_http_upstream_least_conn_module
  --without-http_upstream_random_module
                                     disable ngx_http_upstream_random_module
  --without-http_upstream_keepalive_module
                                     disable ngx_http_upstream_keepalive_module
  --without-http_upstream_zone_module
                                     disable ngx_http_upstream_zone_module

  --with-http_perl_module            enable ngx_http_perl_module
  --with-http_perl_module=dynamic    enable dynamic ngx_http_perl_module
  --with-perl_modules_path=PATH      set Perl modules path
  --with-perl=PATH                   set perl binary pathname

  --http-log-path=PATH               set http access log pathname
  --http-client-body-temp-path=PATH  set path to store
                                     http client request body temporary files
  --http-proxy-temp-path=PATH        set path to store
                                     http proxy temporary files
  --http-fastcgi-temp-path=PATH      set path to store
                                     http fastcgi temporary files
  --http-uwsgi-temp-path=PATH        set path to store
                                     http uwsgi temporary files
  --http-scgi-temp-path=PATH         set path to store
                                     http scgi temporary files

  --without-http                     disable HTTP server
  --without-http-cache               disable HTTP cache

  --with-mail                        enable POP3/IMAP4/SMTP proxy module
  --with-mail=dynamic                enable dynamic POP3/IMAP4/SMTP proxy module
  --with-mail_ssl_module             enable ngx_mail_ssl_module
  --without-mail_pop3_module         disable ngx_mail_pop3_module
  --without-mail_imap_module         disable ngx_mail_imap_module
  --without-mail_smtp_module         disable ngx_mail_smtp_module

  --with-stream                      enable TCP/UDP proxy module
  --with-stream=dynamic              enable dynamic TCP/UDP proxy module
  --with-stream_ssl_module           enable ngx_stream_ssl_module
  --with-stream_realip_module        enable ngx_stream_realip_module
  --with-stream_geoip_module         enable ngx_stream_geoip_module
  --with-stream_geoip_module=dynamic enable dynamic ngx_stream_geoip_module
  --with-stream_ssl_preread_module   enable ngx_stream_ssl_preread_module
  --without-stream_limit_conn_module disable ngx_stream_limit_conn_module
  --without-stream_access_module     disable ngx_stream_access_module
  --without-stream_geo_module        disable ngx_stream_geo_module
  --without-stream_map_module        disable ngx_stream_map_module
  --without-stream_split_clients_module
                                     disable ngx_stream_split_clients_module
  --without-stream_return_module     disable ngx_stream_return_module
  --without-stream_set_module        disable ngx_stream_set_module
  --without-stream_upstream_hash_module
                                     disable ngx_stream_upstream_hash_module
  --without-stream_upstream_least_conn_module
                                     disable ngx_stream_upstream_least_conn_module
  --without-stream_upstream_random_module
                                     disable ngx_stream_upstream_random_module
  --without-stream_upstream_zone_module
                                     disable ngx_stream_upstream_zone_module

  --with-google_perftools_module     enable ngx_google_perftools_module
  --with-cpp_test_module             enable ngx_cpp_test_module

  --add-module=PATH                  enable external module
  --add-dynamic-module=PATH          enable dynamic external module

  --with-compat                      dynamic modules compatibility

  --with-cc=PATH                     set C compiler pathname
  --with-cpp=PATH                    set C preprocessor pathname
  --with-cc-opt=OPTIONS              set additional C compiler options
  --with-ld-opt=OPTIONS              set additional linker options
  --with-cpu-opt=CPU                 build for the specified CPU, valid values:
                                     pentium, pentiumpro, pentium3, pentium4,
                                     athlon, opteron, sparc32, sparc64, ppc64

  --without-pcre                     disable PCRE library usage
  --with-pcre                        force PCRE library usage
  --with-pcre=DIR                    set path to PCRE library sources
  --with-pcre-opt=OPTIONS            set additional build options for PCRE
  --with-pcre-jit                    build PCRE with JIT compilation support
  --without-pcre2                    do not use PCRE2 library

  --with-zlib=DIR                    set path to zlib library sources
  --with-zlib-opt=OPTIONS            set additional build options for zlib
  --with-zlib-asm=CPU                use zlib assembler sources optimized
                                     for the specified CPU, valid values:
                                     pentium, pentiumpro

  --with-libatomic                   force libatomic_ops library usage
  --with-libatomic=DIR               set path to libatomic_ops library sources

  --with-openssl=DIR                 set path to OpenSSL library sources
  --with-openssl-opt=OPTIONS         set additional build options for OpenSSL

  --with-debug                       enable debug logging

nginx导入其他nginx配置文件:

sh 复制代码
incloud filepath # 可以用是绝对路径,也可以是相对路径 此指令可以放在任意地方

3.nginx常用命令

3.1 查看nginx版本号

sh 复制代码
./nginx -v

3.2 停止nginx

sh 复制代码
./nginx -s stop

3.3 启动nginx

sh 复制代码
# 启动nginx时指定配置文件
./nginx -c /www/server/nginx/conf/nginx.conf
# 直接启动nginx
./nginx

3.4 重新加载nginx

sh 复制代码
./nginx -s reload

3.5 nginx配置文件的位置

sh 复制代码
#在安装执行 ./configure --prefix=/web/nginx-install 指定安装目录路径下的conf目录下 nginx.conf就是配置文件

3.6 nginx 的组成部分

  • nginx 配置文件有三部分组成

3.6.1 全局块

从配置文件开始到 events 块之间的内容,主要会设置一些影响nginx 服务器整体运行的配置指令,主要包括配 置运行 Nginx 服务器的用户(组)、允许生成的 worker process 数,进程 PID 存放路径、日志存放路径和类型以 及配置文件的引入等。

比如上面第一行配置的:

sh 复制代码
  worker_processes  1;

这是 Nginx 服务器并发处理服务的关键配置,worker_processes 值越大,可以支持的并发处理量也越多,但是 会受到硬件、软件等设备的制约。

3.6.2 events块

sh 复制代码
events {
    worker_connections  1024;
}

events 块涉及的指令主要影响 Nginx 服务器与用户的网络连接,常用的设置包括是否开启对多 work process 下的网络连接进行序列化,是否 允许同时接收多个网络连接,选取哪种事件驱动模型来处理连接请求,每个 word process 可以同时支持的最大连接数等。

上述例子就表示每个 work process 支持的最大连接数为 1024.

这部分的配置对 Nginx 的性能影响较大,在实际中应该灵活配置。

3.6.2 http块

sh 复制代码
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;
        }
    }
}

这算是 Nginx 服务器配置中最频繁的部分,代理、缓存和日志定义等绝大多数功能和第三方模块的配置都在这里。需要注意的是:http 块也可以包括 http全局块、server 块。

http全局块

http全局块配置的指令包括文件引入、MIME-TYPE 定义、日志自定义、连接超时时间、单链接请求数上限等。

server 块

这块和虚拟主机有密切关系,虚拟主机从用户角度看,和一台独立的硬件主机是完全一样的,该技术的产生是为了 节省互联网服务器硬件成本。

每个 http 块可以包括多个 server 块,而每个 server 块就相当于一个虚拟主机。

而每个 server 块也分为全局 server 块,以及可以同时包含多个 locaton 块。

全局 server 块

最常见的配置是本虚拟机主机的监听配置和本虚拟主机的名称或IP配置。

location 块

一个 server 块可以配置多个 location 块。

这块的主要作用是基于 Nginx 服务器接收到的请求字符串(例如 server_name/uri-string),对虚拟主机名称 (也可以是IP 别名)之外的字符串(例如 前面的 /uri-string)进行匹配,对特定的请求进行处理。 地址定向、数据缓 存和应答控制等功能,还有许多第三方模块的配置也在这里进行。

4.nginx实战篇

4.1 nginx配置请求转发

我们新增一个server模块,做出如下配置

sh 复制代码
    server {
        listen       8080;
        server_name  compass.cq.cn;
        location / {
            proxy_pass http://compass.cq.cn:8003;
        }
    }
    
# 假设我请求的是 http://compass.cq.cn:8080/accountBook/jsonp/test?version=1
# 最终转发的地址为: http://compass.cq.cn:8003/accountBook/jsonp/test?version=1 由他处理后返回给nginx,nginx返回给客户端

4.2 根据请求前缀转发到不同的服务

为了测试方便我部署了一个简单的springboot查询,接口代码如下:

java 复制代码
    @ResponseBody
    @GetMapping("/test")
    public ResponseResult<Map> test(@RequestParam("version") String version) {
        String appName = System.getProperty("app.name");
        log.info("# 系统参数:" + appName);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("version", version);
        map.put("appName", appName);
        return ResponseUtil.success(map);
    }
// 然后分别启动这两个应用程序
// java -jar  -Dserver.port=8003 -Dapp.name=user  compass-account-0.0.1-SNAPSHOT.jar
// java -jar  -Dserver.port=8004 -Dapp.name=order  compass-account-0.0.1-SNAPSHOT.jar

返回结果示例: 返回一个参数version和当前程序的服务名

json 复制代码
# 请求 http://compass.cq.cn:8004/accountBook/jsonp/test?version=1
{
    "code": "200",
    "message": "操作成功",
    "responseTime": "2023-07-22 09:21:29",
    "mac": "fa-20-20-21-44-69",
    "option": null,
    "data": {
        "appName": "orderr",
        "version": "1"
    }
}

nginx.conf 配置如下:

sh 复制代码
    server {
        listen       8080;
        server_name  compass.cq.cn;
        location  /user/ {
            proxy_pass http://compass.cq.cn:8003/; # 以/结尾的时候,location后面的/user会被去掉
        }
        location  /order/ {
            proxy_pass http://compass.cq.cn:8004/;
        }
    }
    
    # 请求示例:http://compass.cq.cn:8080/user/accountBook/jsonp/test?version=1 
    # 请求是以 user开头就返回 user ,order开头就返回 order 

4.3 配置负载均衡

4.3.1 轮询(默认)

有n个服务器,挨个进行分配请求,达到雨露均沾的效果

nginx.conf 配置如下:

sh 复制代码
# 配置负载均衡 采用轮询
upstream equilibriumServer {
        server compass.cq.cn:8003;
        server compass.cq.cn:8004;
    }
# 监听8080端口做请求转发    
server {
        listen       8080;
        server_name  compass.cq.cn;
        location  / {
            proxy_pass http://equilibriumServer;
        }
        
    }

4.3.2 ip_hash

ip_hash 每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器

nginx.conf 配置如下:

sh 复制代码
# 配置负载均衡-ip_hash 采用轮询
upstream equilibriumServer {
        ip_hash;
        server compass.cq.cn:8003;
        server compass.cq.cn:8004;
    }
# 监听8080端口做请求转发    
server {
        listen       8080;
        server_name  compass.cq.cn;
        location  / {
            proxy_pass http://equilibriumServer;
        }
        
    }

4.3.3 配置权重

weight 代表权重, 默认为 1,权重越高被分配的客户端越多

nginx.conf 配置

sh 复制代码
# 配置负载均衡 采用轮询+权重 8003访问一次,8004访问5次后才能轮到8003
upstream equilibriumServer {
        server compass.cq.cn:8003 weight=1;
        server compass.cq.cn:8004 weight=5;
    }
# 监听8080端口做请求转发    
server {
        listen       8080;
        server_name  compass.cq.cn;
        location  / {
            proxy_pass http://equilibriumServer;
        }
        
    }

4.3.4 响应优先-fair

air(第三方),按后端服务器的响应时间来分配请求,响应时间短的优先分配。

fail模块下载地址:https://codeload.github.com/gnosek/nginx-upstream-fair/zip/refs/heads/master

解压后放到nginx的安装目录下(configure文件目录所在位置): 然后依次执行下面的命令,然后重启nginx

sh 复制代码
./configure --prefix=/web/nginx-install  --sbin-path=/web/nginx-install/sbin/nginx --conf-path=/web/nginx-install/conf/nginx.conf --pid-path=/usr/local/nginx/logs/nginx.pid  --add-module=/web/nginx-install/nginx-upstream-fair-master

make
make install

# 重新启动nginx

出现错误解决方案:ngx_http_upstream_srv_conf_t'没有名为'default_port'的成员  
在nginx安装路径下的 nginx-upstream-fair-master 目录下执行
Linux: sed -i 's/default_port/no_port/g' ngx_http_upstream_fair_module.c
macOs: sed -i '' 's/default_port/no_port/g' ngx_http_upstream_fair_module.c

nginx.conf 配置

sh 复制代码
# 配置负载均衡 采用响应优先 
upstream equilibriumServer {
        server compass.cq.cn:8003;
        server compass.cq.cn:8004;
        fair;
    }
# 监听8080端口做请求转发    
server {
        listen       8080;
        server_name  compass.cq.cn;
        location  / {
            proxy_pass http://equilibriumServer;
        }
        
    }

4.4 nginx配置https访问

4.4.1.准备好证书和秘钥

如果是云服务器,可以到对应的云服务器上购买ssl证书,我这里是百度云,我以百度云为例子

直达链接:https://console.bce.baidu.com/cas/#/cas/apply/create (这个是免费1年的,可以按需购买不同的证书)

购买完毕后就可以进行在 https://console.bce.baidu.com/cas/#/cas/purchased/common/list 中进行申请,申请成功后就可以用了

点击查看证书就可以看到下载页面,选择 PEM_nginx 进行下载

下载完毕后有2个文件:*.crt结尾的是ssl证书,*.key结尾的是秘钥

4.4.2.检查nginx是否有ssl模块

进入到nginx的sbin目录下 执行 ./nginx -V

如果出现 (configure arguments: --with-http_ssl_module), 则已安装

没有的话请执行:./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module 随后执行make 重新编译一下。此时再查看应该已经安装完毕

nginx的启动和停止命令

sh 复制代码
# 启动
./nginx -s stop
# 停止
./nginx -c /www/server/nginx/conf/nginx.conf

4.4.3.修改nginx配置文件

sh 复制代码
# 配置ssl
server {
    listen  443 ssl;
    server_name  compass.cn;  # localhost修改为您证书绑定的域名。
    root html;
    index index.html index.htm;
    ssl_certificate /www/server/nginx/ssl/compass.cn.crt;   #将domain.pem替换成您证书的文件名。
    ssl_certificate_key  /www/server/nginx/ssl/compass.cn.key;   #将domain.key替换成您证书的密钥文件名。
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;  #使用此加密套件。
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;   #使用该协议进行配置。
    ssl_prefer_server_ciphers on;   
    location / {
        proxy_set_header HOST $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        try_files $uri $uri/ /index.html;
        root  /web/front/dist;  #前端项目dist的完整路径(这是一个前端项目)
        index index.html;
   }
   location ^~ /accountBook/ { #account项目后端服务
     proxy_pass  http://compass.cn:8080;
    }
   location ^~ /account/ {
       # 文件位置: /web/front/static/accountStaticaccount
       root /web/front/static/accountStatic; 
    }
   #account项目静态资源
   location ^~ /back/ {
        # 文件位置: /web/front/static/accountStaticaccount/back
       root /web/front/static/backStatic; 
    } 
   
}
# 在浏览器访问 https://compass.cn 就可以使用https访问到 /web/front/dist下面的前端项目,后端项目也是能访问到的

4.5 配置web前端项目

nginx配配置

sh 复制代码
    server {
			listen    8002;  
			server_name  compass.cq.cn;  # 你自己的域名或ip
			root  /web/front/dist;  #vue文件dist的完整路径
			sendfile        on;
			tcp_nopush      on;
			default_type text/html;
			location / {
				index  /index.html;
				try_files $uri $uri/ /index.html;
	        	}
			error_page   500 502 503 504  /50x.html;
			location = /50x.html {
				root   html;
			}
        }

配置完毕后访问 http://compass.cq.cn:8002 即可访问到前端项目,如果前端路由转发设置的有前缀还得跟上前缀

4.6 自定义错误页面

需要在http块下开启自定义错误页面配置

sh 复制代码
fastcgi_intercept_errors on;      #表明使用自定义错误提示

nginx.conf 配置:

sh 复制代码
   server {
        listen       80;
        server_name  localhost;
        
        location / {
            root   html;
            index  index.html index.htm;
        }

       error_page   404    /404.html;
        location = /404.html {
            root   /web/front/static/errorPage;
        } 
        
      error_page   500  /500.html;
      location = /500.html {
            root   /web/front/static/errorPage;
        }
        
      error_page   500  /503.html;
      location = /503.html {
            root   /web/front/static/errorPage;
        }  
    }
    
#/web/front/static/errorPage 目录结构
errorPage
    ├── 404.html
    ├── 500.html
    └── 503.html

4.7 nginx配置静态资源

静态资源路径结构

sh 复制代码
[root@compass backStatic]# pwd
/web/front/static/backStatic
[root@compass backStatic]# tree 
└── back
    ├── css
    │   └── index.css
    ├── img
    │   └── index.png
    └── js
        └── index.js

nginx.conf 配置:

sh 复制代码
    server {
			listen    8005;  
			server_name  compass.cq.cn;  
			root  /web/front/static;  
			sendfile        on;
			tcp_nopush      on;
			default_type text/html;
			location ~ ^/(images|img|javascript|js|css|vue|flash|media|static)/ {
                    autoindex on;
                    access_log  off;
                    expires     30d;
            }
			error_page   500 502 503 504  /50x.html;
			location = /50x.html {
				root   html;
			}
    }
# 访问img: http://compass.cq.cn:8005/backStatic/back/img/index.png    

如果配置多个项目的静态资源,我们可以这样配置

sh 复制代码
server {
			listen    8005;  
			server_name  compass.cq.cn;  
			root  /web/front/static;  
			sendfile        on;
			tcp_nopush      on;
			default_type text/html;
			location ^~ /account/ {
       			root /web/front/static/accountStatic; #account项目静态资源
     		}
   			location ^~ /back/ {
       			root /web/front/static/backStatic; #back项目静态资源
    		} 
 }

4.8 nginx实现文件预览

在http{} 内添加功能

sh 复制代码
autoindex on;          #自动显示目录
autoindex_exact_size off;   #人性化方式显示文件大小否则以byte显示
autoindex_localtime on;    #按服务器时间显示,否则以gmt时间显示

server配置

sh 复制代码
server {
        listen 80;
        server_name compass.cq.cn;
        charset utf-8,gbk;
        root /common-file;
}

4.9 防盗链配置

什么是防盗链?

  • 在实际生产过程中,我们线上的图片等静态资源,经常会被其他网站盗用,他们发大财的同时,成本确实我们在买单,下面来说下,如何杜绝这种行为。
  • 应该说只要是静态资源都是可以防盗链的,只需要在Server字段加上几行代码即可。众所周知网站出名了后,会有各种刁民来找茬的,最常见的就是爬你网站的东西。
  • 关于防盗链这里不得不提一下网页的加载顺序是先加载HTML相关的内容,然后解析HTML的内容,那些需要加载图片,那些需要加载文件,是逐步加载的,所以可以在加载静态资源的时候做防盗链的操作,例如:在加载图片的时候直接跳转去其他链接,或者直接返回404,403等错误代码,拒绝它的请求。

如何区分哪些是不正常的用户?

  • HTTP Referer是Header的一部分,当浏览器向Web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理,例如防止未经允许的网站盗链图片、文件等。因此HTTP Referer头信息是可以通过程序来伪装生成的,所以通过Referer信息防盗链并非100%可靠,但是,它能够限制大部分的盗链情况.
  • 比如在www.google.com 里有一个 www.baidu.com 链接,那么点击这个www.baidu.com ,它的header 信息里就有:Referer=http://www.google.com

nginx配置防盗链

sh 复制代码
    server {
			listen    8005;  
			server_name  compass.cq.cn;  
			root  /web/front/static;  
			sendfile        on;
			tcp_nopush      on;
			default_type text/html;
			location ~ ^/(images|img|javascript|js|css|vue|flash|media|static)/ {
                access_log  off;
                expires     7d;
            }
            # 配置防盗链
            location ~* \.(jpeg|tiff|jpeg|png|webapp|gif|js|css|html)$ {  
                valid_referers none  blocked compass.cq.cn 180.76.113.13;
                if ($invalid_referer) { 
                    # 方式1:直接返回403
                    # return 403 ;
                    # 方式2:统一返回一张防盗图片
                    rewrite ^/  http://compass-account.oss-cn-beijing.aliyuncs.com/img/fd.png;
                }
            }  
    }

经过诸多实战案例:相信大家已经对nginx的作用和基础用法有一定的了解,接下来将是对nginx的细化讲解,对配置以及原理讲解,以及一些更高级的用法。

4.10.nginx集群

前边我们学习了反向代理、负载均衡、动静分离,但试想一下,如果Nginx挂掉了,那么服务肯定就没有了,有没有一种解决方案,可以保证Nginx挂掉了,服务也可以照常使用,答案肯定是有的,这就是我们接下来要学习的高可用集群,采用的是一主一备的模式,当主节点Nginx挂掉,备份服务器Nginx立刻跟上,这样就保证了服务的高可用性。

4.10.1 安装主节点keepalived

安装keepalived:

sh 复制代码
yum install -y keepalived

删除keepalived的配置文件:

sh 复制代码
rm -f /etc/keepalived/keepalived.conf

新增keepalived的配置文件:

sh 复制代码
 vim /etc/keepalived/keepalived.conf

注意:一定要注意router_id、state、interface的值

sh 复制代码
! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   #邮件服务器通知地址(暂不配置,默认即可)
   smtp_server 192.168.200.1
   #邮件服务器超时时间(暂不配置,默认即可)
   smtp_connect_timeout 30
   #当前虚拟机的IP地址
   router_id 192.168.75.2
}

vrrp_script Monitor_Nginx {
 script "/etc/keepalived/nginx_check.sh"    #检测脚本执行的路径
 interval 2                                 #检测脚本执行的间隔
 weight 2                                   #检测脚本执行的权重
}

vrrp_instance VI_1 {
    state MASTER         #标识这个机器是MASTER还是BACKUP
    interface eth0       #当前机器的网卡名称  
    virtual_router_id 51 #虚拟路由的编号,主备必须一致
    priority 100         #主、备机取不同的优先级,主机值较大,备份机值较小
    advert_int 1         #(VRRP Multicast广播周期秒数)
    authentication {
        auth_type PASS   #(VRRP认证方式)
        auth_pass admin   #(密码)
    }
    track_script {
		Monitor_Nginx #(调用nginx进程检测脚本)
	}
    virtual_ipaddress {
       192.168.75.1  #虚拟IP地址
    }
}

新增keepalived的检测脚本:

sh 复制代码
vim /etc/keepalived/nginx_check.sh
sh 复制代码
#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process" | grep -v grep )" == "" ]
 then
 killall keepalived
fi

启动keepalived服务:

sh 复制代码
systemctl enable keepalived.service
service keepalived start 

4.10.2 安装从节点keepalived

安装keepalived:

sh 复制代码
yum install -y keepalived

删除keepalived的配置文件:

sh 复制代码
rm -f /etc/keepalived/keepalived.conf

新增keepalived的配置文件:

sh 复制代码
 vim /etc/keepalived/keepalived.conf

注意:一定要注意router_id、state、interface的值

sh 复制代码
! Configuration File for keepalived

global_defs {
   notification_email {
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   #邮件服务器通知地址(暂不配置,默认即可)
   smtp_server 192.168.200.1
   #邮件服务器超时时间(暂不配置,默认即可)
   smtp_connect_timeout 30
   #当前虚拟机的IP地址
   router_id 192.168.75.3
}

vrrp_script Monitor_Nginx {
 script "/etc/keepalived/nginx_check.sh"    #检测脚本执行的路径
 interval 2                                 #检测脚本执行的间隔
 weight 2                                   #检测脚本执行的权重
}

vrrp_instance VI_1 {
    state BACKUP         #标识这个机器是MASTER还是BACKUP
    interface eth0       #当前机器的网卡名称  
    virtual_router_id 51 #虚拟路由的编号,主备必须一致
    priority 100         #主、备机取不同的优先级,主机值较大,备份机值较小
    advert_int 1         #(VRRP Multicast广播周期秒数)
    authentication {
        auth_type PASS   #(VRRP认证方式)
        auth_pass admin   #(密码)
    }
    track_script {
		Monitor_Nginx #(调用nginx进程检测脚本)
	}
    virtual_ipaddress {
       192.168.75.1  #虚拟IP地址
    }
}

新增keepalived的检测脚本:

sh 复制代码
vim /etc/keepalived/nginx_check.sh
sh 复制代码
#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process" | grep -v grep )" == "" ]
 then
 killall keepalived
fi

启动keepalived服务:

sh 复制代码
systemctl enable keepalived.service
service keepalived start 

到这里就配置完成了,使用虚拟ip进行访问即可。

4.11 nginx开启zip压缩

sh 复制代码
http{

    # 开启压缩功能
    gzip on;
    # 设置压缩级别
    gzip_comp_level 6;
    # 设置压缩类型
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    # 设置最小压缩文件大小
    gzip_min_length 1000;
    # 设置压缩缓冲区大小
    gzip_buffers 4 32k;
    # 设置压缩后数据的缓存时间
    gzip_proxied any;
    # 设置压缩比例
    gzip_vary on;
    # 过滤掉IE6等不支持压缩的浏览器
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";
    
    server{
      ...
    }
}

4.12 nginx设置文件上传大小限制

sh 复制代码
http {
    client_max_body_size 20m;
}

4.12 nginx跨域处理

sh 复制代码
 server {
	listen 443 ssl;
	server_name   这里是域名;
    #定义跨域变量
	set $cors_origin "";
    #访问的域名与填写的域名比较
    if ($http_origin ~* "^这里填写调用我们系统的域名地址$") {
            set $cors_origin $http_origin;
    }
   //这里填*就是任何域名都允许跨域
    add_header Access-Control-Allow-Origin $cors_origin;
    #CORS请求默认不发送Cookie和HTTP认证信息。但是如果要把Cookie发到服务器,要服务器同意,指定 
    #Access-Control-Allow-Credentials字段。
	add_header Access-Control-Allow-Credentials 'true';
    #设置跨域请求允许的Header头信息字段,以逗号分隔的字符串
    add_header Access-Control-Allow-Headers 'Origin,X-Requested-With,Content-Type,Accept,Authorization,token';
    #设置跨域允许的请求
    add_header Access-Control-Allow-Metthods 'POST,GET,PUT,OPTIONS,DELETE';
 
     # 预检请求处理
        if ($request_method = OPTIONS) {
                return 204;
        }

4.13 nginx权限控制

权限控制指令:allow 和 deny

allow指令:用于设置允许访问Nginx的客户端IP,语法结构为:allow address CIDR all;

  • address:允许访问的客户端的IP,不支持同时设置多个。如果有多个P需要设置,需要重复使用allow指令。
  • CIDR:允许访问的客户端的CIDR地址,例如202.80.18.23/25,前面是32位P地址,后面"/25"代表该I地址中前25位是网络部分,其余位代表主机部分。
  • all:代表允许所有客户端访问。

从Nginx 0.8.22版本以后,该命令也支持IPv6地址,比如:allow 2620:100:e000::8001;

另一个指令是deny,作用刚好和 allow指令相反,它用于设置禁止访问Nginx 的客户端IP,语法结构为:

deny addressI CIDR all;

  • address:禁止访问的客户端的IP,不支持同时设置多个。如果有多个P需要设置,需要重复使用deny指令。
  • CIDR:禁止访问的客户端的CIDR地址。all,代表禁止所有客户端访问。

就是在同一个块下的两个权限指令,先出现的设置会覆盖后出现的设置(也就是谁先触发,谁起作用)

5. Nginx配置详解

Nginx是通过配置文件来做到各个功能的实现的。Nginx的配置文件的格式非常合乎逻辑,学习这种格式以及如何使用这种每个部分是基础,这将帮助我们有可能手工创建一个配置文件。

5.1 nginx配置整体架构图

5.2 全局块

配置影响nginx全局的指令。主要包括:

  • 配置运行Nginx服务器用户(组)
  • worker process数
  • Nginx进程
  • PID存放路径错误日志的存放路径
  • 一个nginx进程打开的最多文件描述符数目
sh 复制代码
#配置worker进程运行用户(和用户组),nobody也是一个linux用户,一般用于启动程序,没有密码
user nobody;
#user www www;

#配置工作进程数目,根据硬件调整,通常等于CPU数量或者2倍于CPU数量
worker_processes 1;

#配置全局错误日志及类型,[debug | info | notice | warn | error | crit],默认是error
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#配置进程pid文件
pid logs/nginx.pid;

#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。
worker_rlimit_nofile 65535;

5.3 events块

配置影响nginx服务器或与用户的网络连接。主要包括:

  • 事件驱动模型的选择
  • 最大连接数的配置
sh 复制代码
#参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
#epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;

#单个进程最大连接数(最大连接数=连接数*进程数)
worker_connections 65535;

5.4 http块

可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。主要包括:

  • 定义MIMI-Type
  • 自定义服务日志
  • 允许sendfile方式传输文件
  • 连接超时时间
  • 单连接请求数上限
sh 复制代码
#常见的一些基础配置
include mime.types; #文件扩展名与文件类型映射表
default_type application/octet-stream; #默认文件类型
charset utf-8; #默认编码
server_names_hash_bucket_size 128; #服务器名字的hash表大小
client_header_buffer_size 32k; #上传文件大小限制
large_client_header_buffers 4 64k; #设定请求缓冲
client_max_body_size 8m; #设定请求缓冲
sendfile on; #开启高效文件传输模式,对于普通应用设为on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。
tcp_nopush on; #防止网络阻塞
tcp_nodelay on; #防止网络阻塞
keepalive_timeout 120; #长连接超时时间,单位是秒

#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。
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;

#gzip模块设置
gzip on; #开启gzip压缩输出
gzip_min_length 1k; #最小压缩文件大小
gzip_buffers 4 16k; #压缩缓冲区
gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
gzip_comp_level 2; #压缩等级
gzip_types text/plain application/x-javascript text/css application/xml; #压缩类型
gzip_vary on; #增加响应头'Vary: Accept-Encoding'
limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用

5.5 server块

配置虚拟主机的相关参数,一个http中可以有多个server。主要包括:

  • 配置网络监听
  • 配置https服务
  • 基于名称的虚拟主机配置
  • 基于IP的虚拟主机配置
sh 复制代码
#虚拟主机的常见配置
server {
    listen       80; #配置监听端口
    server_name  localhost; #配置服务名
    charset utf-8; #配置字符集
    access_log  logs/host.access.log  main; #配置本虚拟主机的访问日志
    
    location / {
        root html; #root是配置服务器的默认网站根目录位置,默认为nginx安装主目录下的html目录
        index index.html index.htm; #配置首页文件的名称
    }
    
    error_page 404             /404.html; #配置404错误页面
    error_page 500 502 503 504 /50x.html; #配置50x错误页面
}

#配置https服务,安全的网络传输协议,加密传输,端口443
server {
    listen       443 ssl;
    server_name  localhost;

    ssl_certificate      cert.pem;
    ssl_certificate_key  cert.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;
    }
}

5.location

配置请求的路由,以及各种页面的处理情况。主要包括:

  • 请求根目录配置更改
  • 网站默认首页配置
  • location的URI
sh 复制代码
root html; #root是配置服务器的默认网站根目录位置,默认为nginx安装主目录下的html目录
index index.html index.htm; #配置首页文件的名称

proxy_pass http://127.0.0.1:88; #反向代理的地址
proxy_redirect off; #是否开启重定向
#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
#以下是一些反向代理的配置,可选。
client_max_body_size 10m; #允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置
proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;  #设定缓存文件夹大小

5.1 root

root: location中root指定的只是相对路径,需要和路径结合起来映射地址,比如

sh 复制代码
location ^~/static/ {	# 这里的root需要和路径结合使用,即是映射的文件位置为 /usr/login/static
    root /usr/login/; 
    index index.html
}

5.2 alias

alias: alias指定的是绝对路径,不会和location中的路径结合使用,而是直接使用地址映射到文件,比如

sh 复制代码
location ^~/static/ {	## 不会路径结合映射地址,那么这里就会直接映射到/usr/login/文件夹下的文件
    alias /usr/login/; 
    index index.html
}

如果定义的路径是文件夹,那么需要使用/结尾

一旦配置请求location映射到了指定的位置,那么下面全部的文件夹和文件都可以映射到,不需要在配置对其的映射,比如 ,但是如果使用其中的文件名重新映射了地址,那么这个路径将不能使用

5.3 路径匹配

  • = 开头表示精确匹配。如 A 中只匹配根目录结尾的请求,后面不能带任何字符串;
  • ^~ 开头表示uri以某个常规字符串开头,不是正则匹配;
  • ~ 开头表示区分大小写的正则匹配;
  • ~* 开头表示不区分大小写的正则匹配;
  • / 通用匹配, 如果没有其它匹配,任何请求都会匹配到。

一个location定义可以是一个前缀字符串,也可以是一个正则表达式。正则表达式使用的时候要在前面用"*"修饰符(用于不区分大小写匹配),或者""修饰符(用于区分大小写)。为了找到请求匹配的location,nginx首先检查location定义,用前缀字符串(这些location成为前缀location)。其中,最长匹配前缀的location会被选中并记住。然后,检查正则表达式,按照它们在配置文件中出现的顺序。对正则表达式的搜索在第一次匹配时终止,并使用相应的配置。如果没有找到与正则表达式的匹配,则使用前面记住的前缀位置的配置。

1、用前缀字符串(前缀location)匹配URL,并且选中并记住最长匹配前缀的location(注意:是在匹配的里面记住最长的那个)

2、按照正则表达式在配置文件中出现的顺序依次去匹配,当匹配到第一个以后立即停止,并使用与之相应的那个location。如果没有一个正则表达式匹配,则使用之前记住的那个前缀location。

以上,我们可以得出一个结论:优先使用正则表达式,如果没有匹配的正则表达式发现,则使用匹配的最长前缀字符串location

sh 复制代码
 # 精确匹配 / ,主机名后面不能带任何字符串
location  = / {
  [ configuration A ]
}

 # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求 但是正则和最长字符串会优先匹配
location  / {
  [ configuration B ]
}

 # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索
location /documents/ { 
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration C ]
}

location ~ /documents/Abc {  # 匹配任何以 /documents/Abc 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration CC ]
}

 # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。
location ^~ /images/ { 
  [ configuration D ]
}

 # 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则
location ~* \.(gif|jpg|jpeg)$ {  # 匹配所有以 gif,jpg或jpeg 结尾的请求
 
  [ configuration E ]
}

 # 字符匹配到 /images/,继续往下,会发现 ^~ 存在
location /images/ { 
  [ configuration F ]
}

 # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在
location /images/abc { 
  # F与G的放置顺序是没有关系的
  [ configuration G ]
}

 # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用
location ~ /images/abc/ { 
  # 因为都是正则匹配,优先级一样,选择最上面的
    [ configuration H ]
}

 # js开始以.js结尾
location ~* /js/.*/\.js{
   [ configuration I ]
}

优先级:( location = ) > ( location 完整路径 ) > ( location ^~ 路径 ) > ( location ,* 正则顺序 ) > ( location 部分起始路径 ) > ( / )

推荐使用:

sh 复制代码
#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。#这里是直接转发给后端应用服务器了,也可以是一个静态首页# 第一个必选规则

location = / {
    proxy_pass http://tomcat:8080/index
}

# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用

location ^~ /static/ {
    root /webroot/static/;
}location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
#第三个规则就是通用规则,用来转发动态请求到后端应用服务器#非静态文件请求就默认是动态请求,自己根据实际把握#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了
location / {
    proxy_pass http://tomcat:8080/
}

5.4 proxy_pass

在nginx中配置proxy_pass代理转发时,如果在proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走。

假设下面四种情况分别用 http://192.168.1.1/proxy/test.html 进行访问。

sh 复制代码
# 第一种:
location /proxy/ {
    proxy_pass http://127.0.0.1/;
}
# 代理到URL:http://127.0.0.1/test.html

# 第二种(相对于第一种,最后少一个 / )
location /proxy/ {
    proxy_pass http://127.0.0.1;
}
# 代理到URL:http://127.0.0.1/proxy/test.html

# 第三种:
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa/;
}
# 代理到URL:http://127.0.0.1/aaa/test.html

# 第四种(相对于第三种,最后少一个 / )
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa;
}
# 代理到URL:http://127.0.0.1/aaatest.html

6.Nginx原理分析

6.1 nginx线程模型

Nginx默认采用多进程工作方式,Nginx启动后,会运行一个master进程和多个worker进程。其中master充当整个进程组与用户的交互接口,同时对进程进行监护,管理worker进程来实现重启服务、平滑升级、更换日志文件、配置文件实时生效等功能。worker用来处理基本的网络事件,worker之间是平等的,他们共同竞争来处理来自客户端的请求。

6.2 worker的工作模式?

worker对于连接是采用争抢的模式,谁先抢到就先交给谁处理,如果想要重新更新配置,由于已经抢到任务的worker不会参与争抢,那些空闲的worker就会去争抢连接,拿到连接后会自动更新配置信息,当那些有任务的worker完成任务后,会自动更新配置,这样就实现了无缝热部署。由于每个worker是独立的进程,如果有其中的一个worker出现问题,并不会影响其它worker继续进行争抢,在实现请求的过程,不会造成服务中断,建议worker数和服务器的cpu数相等是最为适宜的。

6.3 如何计算worker连接数?

  • 如果只访问nginx的静态资源,一个发送请求会占用了 woker 的 2 个连接数
  • 而如果是作为反向代理服务器,一个发送请求会占用了 woker 的 4 个连接数

6.4 如何计算最大的并发数?

  • 如果只访问nginx的静态资源,最大并发数量应该是: worker_connections * worker_processes / 2
  • 而如果是作为反向代理服务器,最大并发数量应该是:worker_connections * worker_processes / 4
相关推荐
乘云数字DATABUFF3 天前
5分钟部署开源APM Databuff:OpenTelemetry全链路追踪入门实战
运维·后端
荣--5 天前
一键部署不是为了省时间 —— 它是把"买来的 PaaS"变成"自己的平台"的拐点
运维·zabbix·工程化·一键部署·平台化·边界设计
江华森5 天前
动手实战学 Docker — 从零到集群编排完全指南
运维
Avan_菜菜6 天前
FRP 内网穿透完整实战:从 HTTP 映射到 HTTPS 自签代理
运维·nginx·https
SelectDB7 天前
Litefuse 开源并推出单进程轻量模式,25 秒就能跑起来的 Agent 可观测与评估平台
运维·后端·自动化运维
XIAOHEZIcode8 天前
Linux系统鼠标偏移常见原因以及修复方案
linux·运维·游戏
用户0328472220709 天前
如何搭建本地yum源(上)
运维
ping某10 天前
为什么 Nginx 明明监听了 80,转发后端时却用了 4xxxx 端口?
后端·nginx
大树8812 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠12 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql