文章目录

  • 1 Nginx简介
  • 1.1 Nginx搭建
  • 1.1.1 解压和准备
  • 1.1.1.1 准备环境
  • 1.1.1.2 解压
  • 1.1.2 配置编译安装
  • 1.1.2.1 配置
  • 1.1.2.1.1 报错一
  • 1.1.2.1.2 报错二
  • 1.1.2.2 编译
  • 1.1.2.3 安装
  • 1.1.3 Nginx 目录结构
  • 1.1.4 启动
  • 2 Nginx配置讲解
  • 2.1 nginx.conf的讲解
  • 2.2 location文件
  • 2.2.1 root和alias区别
  • 2.2.2 location语法
  • 2.2.3 语法
  • 2.2.3.1 return指令
  • 2.2.3.2 rewrite指令
  • 2.2.3.3 error_page指令
  • 2.2.3.4 日志
  • 2.2.3.5 deny 指令
  • 2.3 负载均衡
  • 2.3.1 负载均衡配置文件
  • 2.3.1.1 负载均衡算法
  • 2.3.1.2 负载均衡配置参数说明
  • 2.3.2 使用负载均衡
  • 2.4 include指令
  • 2.4.1 介绍
  • 2.4.2 使用
  • 2.5 nginx中全局变量
  • 2.6 proxy_pass
  • 2.6.1 介绍
  • 2.6.2 示例说明
  • 2.6.3 具体介绍
  • 2.6.4 两个proxy_pass的关系和区别
  • 2.7 proxy_redirect


1 Nginx简介

Nginx是一个很强大的高性能Web反向代理服务器,具有很多优点,Nginx高并发的情况下可以支持高达50000个并发连接数的响应
Nginx是把工作内容平均分给每台服务器,最理想的状态每台服务器的性能都被充分利用

1.1 Nginx搭建

使用的是Centos 6.7环境Nginx的官网http://nginx.org/,在官网下载最新版就可以

nginx 服务端与iis_linux

1.1.1 解压和准备

1.1.1.1 准备环境
  1. 安装gcc环境
yum install gcc-c++
  1. 安装PCRE库,用于解析正则表达式
yum install -y pcre pcre-devel
  1. zlib压缩和解压缩依赖
yum install -y zlib zlib-devel
  1. SSL安全的加密的套接字协议层,用于HTTP安全传输,也就是https
yum install -y openssl openssl-devel
1.1.1.2 解压

解压压缩包:tar -zxvf nginx-1.18.0.tar.gz

1.1.2 配置编译安装

1.1.2.1 配置

编译之前,先创建nginx临时目录,如果不创建,在启动nginx的过程中会报错mkdir /var/temp/nginx -p 在含有configure的文件夹中执行命令

./configure \   
--prefix=/usr/local/nginx \    
--pid-path=/var/run/nginx/nginx.pid \    
--lock-path=/var/lock/nginx.lock \    
--error-log-path=/var/log/nginx/error.log \    
--http-log-path=/var/log/nginx/access.log \    
--with-http_gzip_static_module \    
--http-client-body-temp-path=/var/temp/nginx/client \    
--http-proxy-temp-path=/var/temp/nginx/proxy \    
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \    
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \    
--http-scgi-temp-path=/var/temp/nginx/scgi

\ 代表在命令行中换行,用于提高可读性配置命令

命令

解释

–prefix

指定nginx安装目录

–pid-path

指向nginx的pid

–lock-path

锁定安装文件防止被恶意篡改或者误操作

–error-log-path

错误日志

–http-log-path

日志

–with-http_gzip_static_module

启用zip模块,在线实时压缩数据流

–http-client-body-temp-path

设定客户端请求临时目录

–http-proxy-temp-path

设定http临时代理目录

–http-fastcgi-temp-path

设定fastcgi临时目录

–http-uwsgi-temp-path

设定uwsgi临时目录

–http-scgi-temp-path

设定scgi临时目录

1.1.2.1.1 报错一

使用命名./configure可能报错:

./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre=<path> option.

需要安装包PCRE library,使用命令:yum install pcre -yyum install pcre-devel -y

1.1.2.1.2 报错二

然后继续报错:

./configure: error: the HTTP gzip module requires the zlib library.
You can either disable the module by using --without-http_gzip_module
option, or install the zlib library into the system, or build the zlib library
statically from the source with nginx by using --with-zlib=<path> option.

需要安装包zlib library,使用命令:yum install zlib -yyum install zlib-devel -y

1.1.2.2 编译

在还有MakeFilemakeFile的文件夹中执行make

1.1.2.3 安装

还是在含有MakeFilemakeFile的文件夹中执行make install注意:这时候在使用make PREFIX=path install不会没生效,因为在配置./configure时已经指定了目录了,如果没有指定目录就是默认的/usr/local/nginx,这些路径已经编译到MakeFile里面去了,在用PREFIX指定就不会生效了
具体可参考:Linux命令详解./configure、make、make install 命令

1.1.3 Nginx 目录结构

使用命令tree : tree /usr/local/nginx

/usr/local/nginx
├── client_body_temp
├── conf # Nginx所有配置文件的目录
│ ├── fastcgi.conf # fastcgi相关参数的配置文件
│ ├── fastcgi.conf.default # fastcgi.conf的原始备份文件
│ ├── fastcgi_params # fastcgi的参数文件
│ ├── fastcgi_params.default
│ ├── koi-utf
│ ├── koi-win
│ ├── mime.types # 媒体类型
│ ├── mime.types.default
│ ├── nginx.conf # Nginx主配置文件
│ ├── nginx.conf.default
│ ├── scgi_params # scgi相关参数文件
│ ├── scgi_params.default
│ ├── uwsgi_params # uwsgi相关参数文件
│ ├── uwsgi_params.default
│ └── win-utf
├── fastcgi_temp # fastcgi临时数据目录
├── html # Nginx默认站点目录
│ ├── 50x.html # 错误页面优雅替代显示文件,例如当出现502错误时会调用此页面
│ └── index.html # 默认的首页文件
├── logs # Nginx日志目录
│ ├── access.log # 访问日志文件
│ ├── error.log # 错误日志文件
│ └── nginx.pid # pid文件,Nginx进程启动后,会把所有进程的ID号写到此文件
├── proxy_temp # 临时目录
├── sbin # Nginx命令目录
│ └── nginx # Nginx的启动命令
├── scgi_temp # 临时目录
└── uwsgi_temp # 临时目录

1.1.4 启动

./configure --prefix=path指定的path中切换进去,找到sbin文件夹,然后使用./sbin启动

在网页上直接通过ip进行访问,如下图

nginx 服务端与iis_nginx_02


附:

停止 ./nginx -s stop 重启 ./nginx -s reload

2 Nginx配置讲解

2.1 nginx.conf的讲解

./configure --prefix=path指定的path中切换进去,找到conf文件夹,进去后找到nginx.conf文件

#user  nobody;  #设置用户

# auto 自动根据CPU核心数调整Worker进程数量
worker_processes  1;#设置工作进程数

#这个参数表示每个进程允许的最多连接数
events { # 事件区块开始
    # 使用epoll网络模型  
    use epoll;  
    worker_connections  1024; # 每个worker进程支持的最大连接数
} # 事件区块结束

# 网络转发配置
http { # HTTP区块开始
    include       mime.types; # Nginx支持的媒体类型库文件
    default_type  application/octet-stream;  # 默认的媒体类型
    #access_log  logs/access.log  main;
	sendfile        on; # 开启高效传输模式
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65; # 连接超时

    #gzip  on;

    server { # 第一个Server区块开始,表示一个独立的虚拟主机站点
        # 之所以输入地址就可以直接访问是端口和地址两个因素决定的
        listen       80;  #默认监听的端口
        #监听的地址,多个地址或者域名用空格分开
        # 默认地址走default_server
        #如果都没有default_server默认的就是第一个server。
        #在只有一个的情况下就不需要区分了。没有域名也只能在一个端口建立一个server。
        # server_name就是访问部署了nginx那台服务器的域名、ip、localhost
        server_name  localhost www.; # 提供服务的域名主机名
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        
        #当直接访问服务器ip没有添加任何uri时的访问信息
        location / {
            root   html; #访问的文件夹,是和从文件夹平级的html文件夹
            index  index.html index.htm;#配置默认文件为html文件夹中的index.html或者index.htm文件           
        }
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html    
		# nginx指令error_page的作用是当发生错误的时候能够显示一个预定义的 uri:/50x.html
        error_page   500 502 503 504  /50x.html; # 出现对应的http状态码时,使用50x.html回应客户
        location = /50x.html {
            root   html; # 指定对应的站点目录为html
        }
    }

注意:当把server-name设置多个: server_name localhost www.;直接访问 www.不会成功,需要改一下本机电脑配置,因为windows不知道这个是不存在的ip 在此路径:C:\Windows\System32\drivers\etc找到host,然后添加nginx服务器所在的地址,以及映射如下

# 添加如下就说明是在把域名映射成这个地址了
192.168.1.1  

2.2 location文件

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

2.2.1 root和alias区别

rootalias的区别:

  • 使用 root时,会到 root + location寻找资源,末尾的/: root则可有可无
  • 使用 alias时, 会到alias后定义的目录中寻找资源 ,但是 alias后面必须要用 /结束,否则会找不到文件的

如下例子:

location /img/ {
    root /var/www/image
}
若按照上述配置的话,访问/img目录里面的文件时, nginx会自动去/var/www/image/img去找

location /img/ {
 	alias /var/www/image/
}
若按照上述配置的话,访问/img目录里面的文件时, nginx会自动去/var/www/image目录找文件

2.2.2 location语法

匹配符

匹配规则

优先级

=

精确匹配

1

^~

以某个字符串开头

2

~

区分大小写的正则匹配

3

~*

不区分大小写的正则匹配

4

!~

区分大小写的不匹配的正则

5

!~*

不区分大小写的不匹配的正则

6

/

通用匹配,任何请求都会匹配到

7

location语法:表示uri方式定位:

  • location = pattern{} :精准定位(=
  • location pattern{} :一般匹配(字符串
  • location ~ pattern{} :区分大小写正则匹配(~),比如:location ~ test{}只匹配带有test的请求,并且在请求的文件夹下有包含test的文件
  • location ^~ pattern{}^~开头,表示uri以某个常规字符串开头,理解为匹配 url路径即可(nginx不对url做编码)
  • location ~* pattern{}~* 开头,表示不区分大小写的正则匹配
  • location !~ pattern{}!~为区分大小写不匹配的正则
  • location !~* pattern{}!~*为不区分大小写不匹配 的正则

2.2.3 语法

if(条件为:= ~ ~*)、returnbreakrewrite~*表示忽略大小写的正则匹配)
-f: 是否为文件、-d:是否为目录、-e:是否存在

#如下为if条件
location ~ test{
 if($remote_addr = 192.168.0.1 ){ #如果来访者ip和这个相同那么就返回去了
  return 401;
 }
 root html;
 index index.html;
}

# 判断浏览器类型的语法
location ~ testAgent{
 if($http_user_agent ~* firefox ){ #如果来访者浏览器不区分大小写包含Firefox就重定向
   rewire ^.*$ /firefox.html; #重定向到firefox.html
   break;  #因为重定向后又是字母,可能还会进这个if方法而无限重定向
 }
 root html;
 index index.html;
}
2.2.3.1 return指令

返回http状态码 和 可选的第二个参数可以是重定向的URL

location /permanently/moved/url {
    return 301 http://www.example.com/moved/here;
}
2.2.3.2 rewrite指令

重写URI请求 rewrite,通过使用rewrite指令在请求处理期间多次修改请求URI,该指令具有一个可选参数和两个必需参数。

  • 第一个(必需)参数是请求URI必须匹配的正则表达式
  • 第二个参数是用于替换匹配URI的URI
  • 可选的第三个参数是可以停止进一步重写指令的处理或发送重定向(代码301或302)的标志
location /users/ {
    rewrite ^/users/(.*)$ /show?user=$1 break;
}
2.2.3.3 error_page指令

使用error_page指令,可以配置NGINX返回自定义页面以及错误代码,替换响应中的其他错误代码,或将浏览器重定向到其他URI。在以下示例中,error_page指令指定要返回404页面错误代码的页面(/404.html)。

error_page 404 /404.html;
2.2.3.4 日志

访问日志:需要开启压缩 gzip on; 否则不生成日志文件,打开log_format、access_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  /usr/local/etc/nginx/logs/host.access.log  main;

gzip  on;
2.2.3.5 deny 指令
# 禁止访问某个目录
location ~* \.(txt|doc)${
    root $doc_root;
    deny all;
}

2.3 负载均衡

找到conf/nginx.conf文件,在http之内,但是在server之外的,是和server平级的,使用upstream关键字

2.3.1 负载均衡配置文件

2.3.1.1 负载均衡算法

nginx默认采用轮询的方式进行负载均衡

  1. 轮询(默认)
    每个请求按时间顺序逐一分配到不同的后端服务器,如果后端某个服务器宕机,能自动剔除故障系统。
upstream backserver {
 server 192.168.0.12;
 server 192.168.0.13;
}
  1. 使用加权轮询
upstream [proxyName] {
    server 192.168.1.173:8080 weight=1;
    server 192.168.1.174:8080 weight=5;
    server 192.168.1.175:8080 weight=2;
}
  1. ip_hash负载均衡
upstream [proxyName] {
    ip_hash
    
    server 192.168.1.173:8080;
    server 192.168.1.174:8080;
    server 192.168.1.175:8080 down;
}

hash算法实际上只会计算192.168.1这段做哈希
使用ip_hash的注意点:
不能把后台服务器直接移除,只能标记down

  1. url hash负载均衡
    必须安装Nginx的hash软件包,按访问urlhash结果来分配请求,使每个url定向到同一个后端服务器,可以进一步提高后端缓存服务器的效率
upstream [proxyName] {
    hash $request_url;

    server 192.168.1.173:8080;
    server 192.168.1.174:8080;
    server 192.168.1.175:8080;
}
  1. 最小连接负载均衡
upstream [proxyName] {
    least_conn;

    server 192.168.1.173:8080;
    server 192.168.1.174:8080;
    server 192.168.1.175:8080;
}
2.3.1.2 负载均衡配置参数说明
upstream myapp{
	server 192.168.1.10:8080 weight=1 max_fails=2 fail_timeout=30s;
	server 192.168.1.11:8080 weight=1 max_fails=2 fail_timeout=30s;
}

配置参数说明:

  • 必须以upstream关键字打头,myapp是自定义名字
  • server:服务器,这个关键字必须要有
  • weight:权重,其值越大,走的可能性也越大,若值一样那么就分一半的访问量
  • max_fails:如果两次进来都在fail_timeout时间内连接不通,就认为这个服务器挂了,默认是1
  • fail_timeout:连接失败时间,默认是10s
  • down:可以标识某个服务已停用,Nginx便不会去访问他了
  • backup:可以标识是备用机,当主机宕机后,备用机会进行服务
  • max_conns:限制最大同时连接数 1.11.5之前只能用于商业版
  • slow_start:单位,权重在指定时间内从1上升到指定值,不适用与hash负载均衡、随机负载均衡 如果在 upstream 中只有一台 server,则该参数失效(商业版才有)
  • keepalive n ; 保持的n个连接数

通常Nginx作为代理服务,负责分发客户端的请求,那么建议开启HTTP长连接,用户减少握手的次数,降低服务器损耗,在upstream中如下配置:

upstream xxx {  
    # 长连接数  
    keepalive 32;  
    # 每个长连接提供的最大请求数  
    keepalived_requests 100;  
    # 每个长连接没有新的请求时,保持的最长时间  
    keepalive_timeout 60s;  
}

2.3.2 使用负载均衡

server {
        listen       80;
        server_name  localhost jingzh.com;
		location / {
           proxy_pass http://myapp; #此处的myapp就是自定义的负载均衡
        }
}

2.4 include指令

2.4.1 介绍

当存在多个域名时,如果所有配置都写在 nginx.conf 主配置文件中,难免会显得杂乱与臃肿。
为了方便配置文件的维护,所以需要进行拆分配置。

主要是在nginx.conf 主配置文件 http{...} 段中加入server{...}的test.conf文件,这其中的test.conf文件可以使用负载均衡里相关标签

2.4.2 使用

nginxconf 目录下创建 vhost 文件夹
vhost 文件夹中创建 .conftest2.com.conf 文件

server {
        listen 8000;
        server_name ;
        location / {
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            # proxy_pass http://xxx.xxx.xxx;
            echo "";    # 输出测试

        }
}
server {
        listen 8000;
        server_name test2.com;
        location / {
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            # proxy_pass http://xxx.xxx.xxx;
            echo "test2.com";    # 输出测试

        }

}

nginx.conf 主配置文件 http{...} 段中加入以下内容:

include vhost/*.conf;    # include 指令用于包含拆分的配置文件

2.5 nginx中全局变量

nginx的配置文件中可以使用的内置变量以美元符$开始,也有人叫全局变量。其中,部分预定义的变量的值是可以改变的。使用方法是在前面加 $ 符号,如$hostname

  • $arg_PARAMETER:这个变量包含GET请求中,如果有变量PARAMETER时的值。
  • $args:这个变量等于请求行中(GET请求)的参数,如foo=123&bar=blahblah,#这个变量等于请求行中的参数,同$query_string
  • $binary_remote_addr:二进制的客户地址。
  • $body_bytes_sent:响应时送出的body字节数数量。即使连接中断,这个数据也是精确的。
  • $content_length:请求头中的Content-length字段。
  • $content_type:请求头中的Content-Type字段。
  • $cookie_COOKIE:cookie COOKIE变量的值
  • $document_root:当前请求在root指令中指定的值。
  • $document_uri:与uri相同。这个变量指当前的请求URI,不包括任何参数(见$args) 如:/2013/81.html
  • $host:请求主机头字段,否则为服务器名称。
  • $hostname:Set to themachine’s hostname as returned by gethostname,如:centos53.localdomain
  • $uri:这个变量指当前的请求URI,不包括任何参数(见$args) 如:/2013/81.html
  • $is_arg:如果有args参数,这个变量等于”?”,否则等于””,空值,如?
  • $http_user_agent:客户端agent信息
  • $http_cookie:客户端cookie信息
  • $limit_rate:这个变量可以限制连接速率。
  • $query_string:与args相同。
  • $request_body:记录POST过来的数据信息
  • $request_body_file:客户端请求主体信息的临时文件名。
  • $request_method:客户端请求的动作,通常为GET或POST。
  • $remote_addr:客户端的IP地址。
  • $remote_port:客户端的端口。
  • $remote_user:已经经过Auth Basic Module验证的用户名。
  • $request_completion:如果请求结束,设置为OK. 当请求未结束或如果该请求不是请求链串的最后一个时,为空(Empty)。
  • $request_method:GET或POST
  • $request_filename:当前请求的文件路径,由root或alias指令与URI请求生成
  • $request:用户请求信息,如:GET ?a=1&b=2 HTTP/1.1
  • $request_uri:包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。不能修改。
  • $scheme:HTTP方法(如http,https)。
  • $server_protocol:请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
  • $server_addr:服务器地址,在完成一次系统调用后可以确定这个值。
  • $server_name:服务器名称。
  • $server_port:请求到达服务器的端口号
  • $status:请求的响应状态码,如:200
  • $http_referer:引用地址

2.6 proxy_pass

2.6.1 介绍

nginx中配置proxy_pass代理转发时,
如果在proxy_pass后面的url加/,表示绝对根路径,则nginx不会加上location中匹配的路径;
如果没有/,表示相对路径,则会加上location匹配的路径。

2.6.2 示例说明

本次测试proxy_passnginx版本号:nginx version: nginx/1.18.0

序号

浏览器中url

location中配置

location末尾有无 /

proxy_pass末尾有无 /

实际url

1

http://192.168.1.1:8000/test1/abc.html

location

/test1 {

proxy_pass http://127.0.0.1/;}



//abc.html

2

http://192.168.1.1:8000/test11/abc.html

location

/test11/ {

proxy_pass http://127.0.0.1/;}



/abc.html

3

http://192.168.1.1:8000/test2/abc.html

location

/test2 {

proxy_pass http://127.0.0.1;}



/test2/abc.html

4

http://192.168.1.1:8000/test22/abc.html

location

/test22/ {

proxy_pass http://127.0.0.1;}



/test22/abc.html

5

http://192.168.1.1:8000/test3/abc.html

location

/test3 {

proxy_pass http://127.0.0.1/aaa/;}



/aaa//abc.html

6

http://192.168.1.1:8000/test33/abc.html

location

/test33/ {

proxy_pass http://127.0.0.1/aaa/;}



/aaa/abc.html

7

http://192.168.1.1:8000/test4/abc.html

location

/test4 {

proxy_pass http://127.0.0.1/aaa;}



/aaa/abc.html

8

http://192.168.1.1:8000/test44/abc.html

location

/test44/ {

proxy_pass http://127.0.0.1/aaa;}



/aaaabc.html

解析说明:

  • proxy_pass末尾无附加路径,比如1~4
    proxy_pass末尾有/,不会附带location中路径,若location末尾有/,则不会附带/,比如序号2,否则/还会出现在实际路径中,比如序号1proxy_pass末尾无/,会附带location中路径,不管location末尾有无/,都会正常比如序号3~4
  • proxy_pass末尾有附加路径,比如5~8
    proxy_pass末尾有/,不会附带location中路径,若location末尾有/,则不会附带/,比如序号6,否则/还会出现在实际路径中,比如序号5proxy_pass末尾无/,依然不会附带location中路径,若location末尾有/,会让匹配到的末尾/不出现,不会在实际地址中有/,比如序号8,若location末尾无/,则会在实际地址中有/,比如序号7

2.6.3 具体介绍

nginx中有两个模块都有proxy_pass指令

  • ngx_http_proxy_moduleproxy_pass
    语法: proxy_pass URL;
    场景: location, if in location, limit_except 说明: 设置后端代理服务器的协议(protocol)和地址(address),以及location中可以匹配的一个可选的URI。协议可以是"http"或"https"。地址可以是一个域名或ip地址和端口,或者一个 unix-domain socket 路径。
  • ngx_stream_proxy_moduleproxy_pass
    语法: proxy_pass address;
    场景: server 说明: 设置后端代理服务器的地址。这个地址(address)可以是一个域名或ip地址和端口,或者一个 unix-domain socket路径。

2.6.4 两个proxy_pass的关系和区别

在两个模块中,两个proxy_pass都是用来做后端代理的指令。
ngx_stream_proxy_module模块的proxy_pass指令只能在server端使用使用, 只需要提供域名或ip地址和端口。可以理解为端口转发,可以是tcp端口,也可以是udp端口。
ngx_http_proxy_module模块的proxy_pass指令需要在location段,location中的if段,limit_except段中使用,处理需要提供域名或ip地址和端口外,还需要提供协议,如"http"或"https",还有一个可选的uri可以配置

2.7 proxy_redirect

proxy_redirect 语法:proxy_redirect [ default|off|redirect replacement ] 默认值:proxy_redirect default 使用字段:http, server, location 如果需要 修改 从被代理服务器传来的应答头中的LocationRefresh字段,可以用这个指令设置。
假设被代理服务器返回Location字段为: http://localhost:8000/two/some/uri/
这个指令:

proxy_redirect http://localhost:8000/two/ http://frontend/one/;

将Location字段重写为http://frontend/one/some/uri/