> 文章列表 > nginx快速入门

nginx快速入门

nginx快速入门

本文应侧重操作应用,复杂原理详见相关理论类笔记

Nginx 快速入门笔记

Nginx 的简介

1. 什么是 nginx

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

2. 正向代理

​ Nginx 不仅可以做反向代理,实现负载均衡。还能用作正向代理来进行上网等功能。

正向代理:如果把局域网外的 Internet 想象成一个巨大的资源库,则局域网中的客户端要访问 Internet,则需要通过代理服务器来访问,这种代理服务就称为正向代理。

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

  • 好处难道是隐藏请求端真实ip?
    • 好处:局域网通过连接公网的服务器访问公网

3. 反向代理

反向代理 : 其实客户端对代理是无感知的,因为客户端不需要任何配置就可以访问,我们只需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据后,在返回给客户端,此时反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器地址,隐藏了真实服务器 IP 地址

  • 其他代理:
    • 拦截代理
    • 修改DNS假装真正服务器?

正向代理:用户知道并主动找代理

反向代理:服务器找了个代理,用户访问服务器的时候只能先找代理

4. 负载均衡

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

	这种架构模式对于早期的系统相对单一,并发请求相对较少的情况下是比较适合的,成本也低。但是随着信息数量的不断增长,访问量和数据量的飞速增长,以及系统业务的复杂度增加,这种架构会造成服务器相应客户端的请求日益缓慢,并发量特别大的时候,还容易造成服务器直接崩溃。很明显这是由于服务器性能的瓶颈造成的问题,那么如何解决这种情况呢?我们首先想到的可能是升级服务器的配置,比如提高 CPU 执行频率,加大内存等提高机器的物理性能来解决此问题,但是我们知道摩尔定律的日益失效,硬件的性能提升已经不能满足日益提升的需求了。最明显的一个例子,天猫双十一当天,某个热销商品的瞬时访问量是极其庞大的,那么类似上面的系统架构,将机器都增加到现有的顶级物理配置,都是不能够满足需求的。那么怎么办呢?

​ 上面的分析我们去掉了增加服务器物理配置来解决问题的办法,也就是说纵向解决问题的办法行不通了,那么横向增加服务器的数量呢?这时候集群的概念产生了,单个服务器解决不了,我们增加服务器的数量,然后将请求分发到各个服务器上,将原先请求集中到单个服务器上的情况改为将请求分发到多个服务器上,将负载分发到不同的服务器,也就是我们所说的负载均衡

5. 动静分离

​ 为了加快网站的解析速度,可以把动态页面和静态页面由不同的服务器来解析,加快解析速度。降低原来单个服务器的压力。

Nginx 的安装

1. 进入 nginx 官网,下载

http://nginx.org/

image-20200702195847326

image-20200702195907197

2. 安装nginx

第一步,安装环境

nginx由C++编写,此处安装最全的c++环境,省得以后装其他c++软件麻烦。

 yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5-devel libidn openssl openssl-devel nss_ldap openldap openldap-devel  openldap-clients  libxslt-devel libevent-devel libtool-ltdl bison libtool vim-enhanced  #libidn-devel openldap-servers ntp

nginx快速入门

第二步,安装nginx

使用源码包的方式安装,将源码解压后用make工具构建工程

image-20200702220819387

压缩包放入usr/src下,并解压 tar -xvf nginx-1.18.0.tar.gz

image-20200702220929023

进入nginx目录下执行 ./configure。如果要安装其他模块的话,可以在./configure时加上参数,如这里安装SSL模块,后续就可以代理https协议了

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

image-20200702221038872

执行完后 再执行 make && make install

安装成功后 usr/local 下会增一个 nginx 文件夹

测试启动 nginx 并在进程中查看

在nginx 目录的 conf 目录下的nginx.conf 可以查看端口号,默认是80

命令:vim nginx.conf

浏览器直接通过ip地址访问,测试能否成功!(这里如果访问不成,进不去,要考虑是否将防火墙关闭!)

防火墙配置(开放端口号)

查看防火墙开放的端口号

firewall-cmd --list-all

publictarget: defaulticmp-block-inversion: nointerfaces: sources: services: dhcpv6-client ssh#ports: 80/tcp	开放的话会有这一行protocols: masquerade: noforward-ports: source-ports: icmp-blocks: rich rules:

设置开放的端口号

firewall-cmd --add-service=http –permanentsudo firewall-cmd --add-port=80/tcp --permanent

重启防火墙

firewall-cmd –reload

sudo systemctl restart firewalld
    ssl_certificate      /etc/nginx/ssl.crt;  # 证书的crt文件所在目录(如果是阿里云申请的证书,就是*.pem文件)ssl_certificate_key  /etc/nginx/ssl.key;  # 证书key文件所在目录(使用绝对路径)

————————————————
版权声明:本文为CSDN博主「SURLIYA」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/SURLIYA/article/details/102854845

nginx 常用操作命令和配置文件

启动命令

在/usr/local/nginx/sbin 目录下执行 ./nginx

关闭命令

在/usr/local/nginx/sbin 目录下执行 ./nginx -s stop

重新加载命令

在/usr/local/nginx/sbin 目录下执行 ./nginx -s reload

nginx.conf 配置文件

​ nginx 默认的配置文件都放在安装目录下的 conf 目录下,而主配置文件nginx.conf 也在其中,后续对 nginx 的使用基本上都是对此配置文件进行相应的修改。

​ 配置文件中有很多#, 开头的表示注释内容。我把一会儿需要的主要内容粘贴如下:

#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       mime.types;default_type  application/octet-stream;#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;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;server {listen       80;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}}

根据上述文件,我们可以很明显的将 nginx.conf 配置文件分为三部分:

第一部分:全局块

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

比如上面第一行配置的:

#user  nobody;
worker_processes  1;

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

第二部分:events 块

比如上面的配置:

events {worker_connections  1024;
}

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

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

	这部分的配置对 Nginx 的性能影响较大,在实际中应该灵活配置。
第三部分:http 块
http {include       mime.types;default_type  application/octet-stream;#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;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;server {listen       80;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#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 块。

1、全局 server 块

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

  • listen : 指定服务器侦听请求的IP地址和端口,如果省略地址,服务器将侦听所有地址,如果省略端口,则使用标准端口

  • server_name : 服务名称,用于配置域名

2、location 块

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

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

  • location : 用于配置映射路径uri对应的配置,一个server中可以有多个location, location后面跟一个uri,可以是一个正则表达式, 当客户端访问的路径满足这个uri时就会执行location块里面的代码
  • root : 根路径,当访问http://localhost/test.html,“/test.html”会匹配到”/”uri, 找到root为/usr/local/var/www/html,用户访问的资源物理地址=root + uri = /usr/local/var/www/html + /test.html
  • index : 设置首页

注意:注意!/chat/和/chat不同!!!配置里写了杠的话,前端请求也要写上!

常见的location路径映射路径有以下几种:

  • = 进行普通字符精确匹配。也就是完全匹配。
  • ^~ 前缀匹配。如果匹配成功,则不再匹配其他location。
  • ~ 表示执行一个正则匹配,区分大小写
  • ~* 表示执行一个正则匹配,不区分大小写
  • /xxx/ 常规字符串路径匹配
  • / 通用匹配,任何请求都会匹配到

以下是按优先级排列说明:

  • 等号类型(=)的优先级最高。一旦匹配成功,则不再查找其他匹配项,停止搜索。
  • ^~类型表达式,不属于正则表达式。一旦匹配成功,则不再查找其他匹配项,停止搜索。
  • 正则表达式类型(~ ~*)的优先级次之。如果有多个location的正则能匹配的话,则使用正则表达式最长的那个。
  • 常规字符串匹配类型。按前缀匹配。
  • / 通用匹配,如果没有匹配到,就匹配通用的

优先级搜索问题:不同类型的location映射决定是否继续向下搜索

  • 等号类型、^~类型:一旦匹配上就停止搜索了,不会再匹配其他location了
  • 正则表达式类型(~ ~*),常规字符串匹配类型/xxx/ : 匹配到之后,还会继续搜索其他其它location,直到找到优先级最高的,或者找到第一种情况而停止搜索

location优先级从高到底:

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

location常用配置,需要时来粘贴

location = / {# 精确匹配/,主机名后面不能带任何字符串 /[ configuration A ]
}
location / {# 匹配所有以 / 开头的请求。# 但是如果有更长的同类型的表达式,则选择更长的表达式。# 如果有正则表达式可以匹配,则优先匹配正则表达式。[ configuration B ]
}
location /documents/ {# 匹配所有以 /documents/ 开头的请求,匹配符合以后,还要继续往下搜索。# 但是如果有更长的同类型的表达式,则选择更长的表达式。# 如果有正则表达式可以匹配,则优先匹配正则表达式。[ configuration C ]
}
location ^~ /images/ {# 匹配所有以 /images/ 开头的表达式,如果匹配成功,则停止匹配查找,停止搜索。# 所以,即便有符合的正则表达式location,也不会被使用[ configuration D ]
}location ~* \\.(gif|jpg|jpeg)$ {# 匹配所有以 gif jpg jpeg结尾的请求。# 但是 以 /images/开头的请求,将使用 Configuration D,D具有更高的优先级[ configuration E ]
}location /images/ {# 字符匹配到 /images/,还会继续往下搜索[ configuration F ]
}location = /test.htm {root   /usr/local/var/www/htm;index  index.htm;
}

nginx 配置实例-反向代理

反向代理实例一

实现效果:使用 nginx 反向代理,访问 www.123.com 直接跳转到 127.0.0.1:8080

反向代理(Reverse Proxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。

简单来说就是真实的服务器不能直接被外部网络访问,所以需要一台代理服务器,而代理服务器能被外部网络访问的同时又跟真实服务器在同一个网络环境,当然也可能是同一台服务器,端口不同而已。

反向代理通过proxy_pass指令来实现。

具体步骤:

1.部署项目

以tomcat上的项目为例,

测试访问(这里需要注意,如果访问不成功,就有可能是你的linux 防火墙没有开8080端口,需要修改下防火墙端口配置):

开放端口8080
sudo firewall-cmd --add-port=8080/tcp --permanent
重启防火墙
firewall-cmd –reload
查看已经开放的端口
firewall-cmd --list-all
4. 反向代理访问过程分析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9j7A4cbt-1682169921382)(null)]

5. 配置反向代理步骤
5.1 本机 host 文件配置

在本机windows 系统的 host 文件进行域名和ip 对应关系的配置。

在hosts文件最后添加如下配置

192.168.88.132	www.123.com		#Linux 主机ip		本机配置的域名

​ 配置完成之后,我们便可以通过 www.123.com:8080 访问到第一步出现的 Tomcat 初始界面。那么如何只需要输入 www.123.com 便可以跳转到 Tomcat 初始界面呢?便用到 nginx的反向代理。

5.2 在 nginx 中进行请求转发配置(反向代理配置)

找到nginx 的配置文件 nginx.conf

[root@bogon bin]# cd /usr/local/nginx/conf
[root@bogon conf]# vim nginx.conf

在 nginx.conf 配置文件中增加如下配置:

    server {listen       80;server_name  192.168.88.132;	#nginx访问地址#charset koi8-r;#access_log  logs/host.access.log  main;location / {proxy_pass http://192.168.88.132:8080;	#转发到目标地址# 其他配置 酌情考虑proxy_http_version 1.1;# 常见ip设置 设置到Headerproxy_set_header  Host $host;proxy_set_header  X-Real-IP  $remote_addr;proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;}# redirect server error pages to the static page /50x.htmlerror_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}

​ 如上配置,我们监听 80 端口,访问域名为 www.123.com,不加端口号时默认为 80 端口,故访问该域名时会跳转到 192.168.88.132:8080 路径上。

5.3 启动nginx测试

在浏览器端输入 www.123.com 结果如下:

注意:修改完nginx.conf 配置文件后,启动nginx 重新加载一下配置文件 ./nginx -s reload

反向代理成功!

反向代理实例二

实现效果:使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务中

nginx 监听端口为 9001,

访问 http://127.0.0.1:9001/edu/ 直接跳转到 127.0.0.1:8081

访问 http://127.0.0.1:9001/vod/ 直接跳转到 127.0.0.1:8082

反向代理配置步骤

1. 准备两个 tomcat

​ 在usr/src 下建立两个文件夹 tomcat8081 tomcat8082,并在这两个文件夹下放入两个tomcat ,并解压。

创建文件夹命令:mkdir tomcat8081,mkdir tomcat8082

解压命令:tar -xvf apache-tomcat-7.0.70.tar.gz

先查看本机的tomcat是否正在运行:ps -ef|grep tomcat,如果正在运行根据运行的进程id号杀死正在运行的tomcat进程 kill 进程id号:

修改两个tomcat的端口号:一个 8081 端口,一个 8082 端口。

进入tomcat 的conf文件夹下,并vi server.xml,修改内容为如下面标记位置。

<?xml version='1.0' encoding='utf-8'?>
<!--Licensed to the Apache Software Foundation (ASF) under one or morecontributor license agreements.  See the NOTICE file distributed withthis work for additional information regarding copyright ownership.The ASF licenses this file to You under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance withthe License.  You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may notdefine subcomponents such as "Valves" at this level.Documentation at /docs/config/server.html-->
<!-- 为避免冲突从8005改为8025 -->
<Server port="8025" shutdown="SHUTDOWN"><Listener className="org.apache.catalina.startup.VersionLoggerListener" /><!-- Security listener. Documentation at /docs/config/listeners.html<Listener className="org.apache.catalina.security.SecurityListener" />--><!--APR library loader. Documentation at /docs/apr.html --><Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /><!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html --><Listener className="org.apache.catalina.core.JasperListener" /><!-- Prevent memory leaks due to use of particular java/javax APIs--><Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /><Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /><Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /><!-- Global JNDI resourcesDocumentation at /docs/jndi-resources-howto.html--><GlobalNamingResources><!-- Editable user database that can also be used byUserDatabaseRealm to authenticate users--><Resource name="UserDatabase" auth="Container"type="org.apache.catalina.UserDatabase"description="User database that can be updated and saved"factory="org.apache.catalina.users.MemoryUserDatabaseFactory"pathname="conf/tomcat-users.xml" /></GlobalNamingResources><!-- A "Service" is a collection of one or more "Connectors" that sharea single "Container" Note:  A "Service" is not itself a "Container",so you may not define subcomponents such as "Valves" at this level.Documentation at /docs/config/service.html--><Service name="Catalina"><!--The connectors can use a shared executor, you can define one or more named thread pools--><!--<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"maxThreads="150" minSpareThreads="4"/>--><!-- A "Connector" represents an endpoint by which requests are receivedand responses are returned. Documentation at :Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)Java AJP  Connector: /docs/config/ajp.htmlAPR (HTTP/AJP) Connector: /docs/apr.htmlDefine a non-SSL HTTP/1.1 Connector on port 8080--><!-- 为避免冲突从8080改为8081 --><Connector port="8081" protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443" /><!-- A "Connector" using the shared thread pool--><!--<Connector executor="tomcatThreadPool"port="8080" protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443" />--><!-- Define a SSL HTTP/1.1 Connector on port 8443This connector uses the BIO implementation that requires the JSSEstyle configuration. When using the APR/native implementation, theOpenSSL style configuration is required as described in the APR/nativedocumentation --><!--<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"maxThreads="150" SSLEnabled="true" scheme="https" secure="true"clientAuth="false" sslProtocol="TLS" />--><!-- Define an AJP 1.3 Connector on port 8009 --><!-- 为避免冲突从8009改为8029 --><Connector port="8029" protocol="AJP/1.3" redirectPort="8443" /><!-- An Engine represents the entry point (within Catalina) that processesevery request.  The Engine implementation for Tomcat stand aloneanalyzes the HTTP headers included with the request, and passes themon to the appropriate Host (virtual host).Documentation at /docs/config/engine.html --><!-- You should set jvmRoute to support load-balancing via AJP ie :<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">--><Engine name="Catalina" defaultHost="localhost"><!--For clustering, please take a look at documentation at:/docs/cluster-howto.html  (simple how to)/docs/config/cluster.html (reference documentation) --><!--<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>--><!-- Use the LockOutRealm to prevent attempts to guess user passwordsvia a brute-force attack --><Realm className="org.apache.catalina.realm.LockOutRealm"><!-- This Realm uses the UserDatabase configured in the global JNDIresources under the key "UserDatabase".  Any editsthat are performed against this UserDatabase are immediatelyavailable for use by the Realm.  --><Realm className="org.apache.catalina.realm.UserDatabaseRealm"resourceName="UserDatabase"/></Realm><Host name="localhost"  appBase="webapps"unpackWARs="true" autoDeploy="true"><!-- SingleSignOn valve, share authentication between web applicationsDocumentation at: /docs/config/valve.html --><!--<Valve className="org.apache.catalina.authenticator.SingleSignOn" />--><!-- Access log processes all example.Documentation at: /docs/config/valve.htmlNote: The pattern used is equivalent to using pattern="common" --><Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"prefix="localhost_access_log." suffix=".txt"pattern="%h %l %u %t &quot;%r&quot; %s %b" /></Host></Engine></Service>
</Server>

修改完成后,到bin目录下 ./startup.sh 运行8082端口的tomcat

同理8082端口的tomcat 同样如上配置并运行启动!

2.为两个tomcat 添加页面

向两个tomcat服务器的webapps下分别创建edu 和 文件夹,并将a.html 和 b.html 分别放入这两个文件夹。(注:a.html 和 b.html 自己随便建立一个,里面输入自己想展示的信息,能够区分是来自不同tomcat 服务器即可)

3. nginx.conf配置反向代理
#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       mime.types;default_type  application/octet-stream;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;server {listen       80;server_name  192.168.88.132;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;proxy_pass http://127.0.0.1:8080;index  index.html index.htm;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}}# another virtual host using mix of IP-, name-, and port-based configuration# 在这里把注释去掉,添加一个server 端口监听9001server {listen       9001;server_name  192.168.88.132;# 在下面 配置转发到不同的tomcat 中的内容 格式:~ /项目名/location ~ /edu/ {proxy_pass http://127.0.0.1:8001;}location ~ /vod/ {proxy_pass http://127.0.0.1:8002;}}
}

配置完成后,开放对外访问的端口号,如果防火墙已经关闭就不用了。

在/nginx/sbin/中执行 ./nginx -s reload 重新加载配置文件。

4. 测试
5. location 指令说明

该指令用于匹配 URL。
语法如下:

  1. = :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配
    成功,就停止继续向下搜索并立即处理该请求。
  2. ~:用于表示 uri 包含正则表达式,并且区分大小写。
  3. ~*:用于表示 uri 包含正则表达式,并且不区分大小写。
  4. ^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配。

注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。

nginx 配置实例-负载均衡

1、实现效果

​ 浏览器地址栏输入地址http://192.168.17.129/edu/a.html,负载均衡效果,平均到80828081 端口中。

2、准备工作

准备两 tomcat 服务器,一台 8082,一台 8081

在两台 tomcat 里面 webapps 目录中,创建名称是 edu 文件夹,在edu 文件夹中创建页面 a.html,用于测试。

3. 在 nginx 的配置文件中进行负载均衡的配置

负载均衡通过upstream指令来实现。

nginx.conf配置如下:

#user  nobody;
worker_processes  1;
events {worker_connections  1024;
}http {include       mime.types;default_type  application/octet-stream;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;# 加上upstream upstream myserver {server  192.168.88.132:8080; #参与负载均衡的服务器地址1server  192.168.88.132:8081; #参与负载均衡的服务器地址2}server {listen       80;server_name  192.168.88.132;#charset koi8-r;#access_log  logs/host.access.log  main;location / {# 加上代理规则proxy_pass http://myserver;root   html;index  index.html index.htm;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}
}

权重

指定轮询几率,weight和访问比率成正比, 也就是服务器接收请求的比例就是各自配置的weight的比例,用于后端服务器性能不均的情况,比如服务器性能差点就少接收点请求,服务器性能好点就多处理点请求。

upstream test {server localhost:8081 weight=1;server localhost:8082 weight=3;server localhost:8083 weight=4 backup;
}

示例是4次请求只有一次被分配到8081上,其他3次分配到8082上。backup是指热备,只有当8081和8082都宕机的情况下才走8083

ip_hash

上面的2种方式都有一个问题,那就是下一个请求来的时候请求可能分发到另外一个服务器,当我们的程序不是无状态的时候(采用了session保存数据),这时候就有一个很大的很问题了,比如把登录信息保存到了session中,那么跳转到另外一台服务器的时候就需要重新登录了,所以很多时候我们需要一个客户只访问一个服务器,那么就需要用iphash了,iphash的每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。

upstream test {ip_hash;server localhost:8080;server localhost:8081;
}

4.访问测试

访问http://192.168.88.132/edu/a.html:第一次访问显示如下:

刷新页面,效果如下:

可以看出,访问该页面的时候,nginx会把请求平均分担到8080和8081两个服务器。

5.nginx分配服务器策略

第一种 轮询策略(默认)

​ 每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,能自动剔除。

第二种 权重策略 weight

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

#例如:upstream myserver {server  192.168.88.132:8080 weight=5; #参与负载均衡的服务器地址1server  192.168.88.132:8081 weight=10; #参与负载均衡的服务器地址2}
# 如上,8080的权重为5 8081权重为10,则nginx 负载均衡分配时,分配的8081比例更大

第三种 ip哈希策略 ip_hash

​ 每个请求按访问 ip 的hash 结果分配,这样每个访客固定访问一个后端服务器,可以解决session问题。

#例如:upstream myserver {ip_hashserver  192.168.88.132:8080; #参与负载均衡的服务器地址1server  192.168.88.132:8081; #参与负载均衡的服务器地址2}
# 如上,每个请求按访问 ip 的hash 结果分配,即:某一个用户访问该服务器,根据该用户的ip地址分配一个ip_hash,并随机分配到端口为8080或者8081的服务器,该用户这个ip下次再访问服务器时,仍然默认访问上次分配的服务器,而不会再次随机分配。

第四种 fair(第三方):

​ 按后端服务器的响应时间来分配请求,响应时间短的优先分配。

#例如:upstream myserver {server  192.168.88.132:8080; #参与负载均衡的服务器地址1server  192.168.88.132:8081; #参与负载均衡的服务器地址2fair}
# 如上,访问该服务器时,通过判断 8080 或者 8081 服务器响应的时间,来进行分配访问,谁的响应时间短,优先访问谁。

Nginx配置实例-动静分离

1. 动静分离简述

​ Nginx 动静分离简单来说就是把动态跟静态请求分开,不能理解成只是单纯的把动态页面和静态页面物理分离。严格意义上说应该是动态请求跟静态请求分开,可以理解成使用 Nginx 处理静态页面Tomcat 处理动态页面。动静分离从目前实现角度来讲大致分为两种,一种是纯粹把静态文件独立成单独的域名,放在独立的服务器上,也是目前主流推崇的方案另外一种方法就是动态跟静态文件混合在一起发布,通过 nginx 来分开

​ 通过location 指定不同的后缀名实现不同的请求转发。通过 expires 参数设置,可以使浏览器缓存过期时间,减少与服务器之前的请求和流量。具体 Expires 定义:是给一个资源设定一个过期时间,也就是说无需去服务端验证,直接通过浏览器自身确认是否过期即可,所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件,不建议使用 Expires 来缓存),我这里设置 3d,表示在这 3 天之内访问这个 URL,发送一个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码304,如果有修改,则直接从服务器重新下载,返回状态码 200。

执行流程图

nginx快速入门

2. 准备工作

liunx 系统中准备静态资源,用于进行访问:

首先在根路径下创建 staticresource 文件夹,并在其中建立 www 和 image文件夹用于存放静态资源:

在www 文件夹中放置一个a.html 在 image 放置lf.jpg

3. 具体配置

在nginx 配置文件中配置静态资源访问

配置内容如下(此处只摘取主体部分):

http {include       mime.types;default_type  application/octet-stream;sendfile        on;keepalive_timeout  65;server {listen       80;server_name  192.168.88.132;#配置静态资源访问location /www/ {root   /staticresource/;index  index.html index.htm;}location /image/{root /staticresource/;autoindex on;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}
}

index.html是安装nginx自带的html

另一个例子

upstream web_servers {  server localhost:8081;  server localhost:8082;  
}server {listen       80;server_name  localhost;set $doc_root /usr/local/var/www;location ~* \\.(gif|jpg|jpeg|png|bmp|ico|swf|css|js)$ {root $doc_root/img;}location / {proxy_pass http://web_servers;# 必须指定Header Hostproxy_set_header Host $host:$server_port;}error_page 500 502 503 504  /50x.html;  location = /50x.html {  root $doc_root;}}

4. 测试查看效果

浏览器中输入地址

http://192.168.88.132/image/lf.jpg

http://192.168.88.132/www/a.html

注意:如果访问图片出现403 Forbidden错误,可能是因为nginx.conf 的第一行user配置不对,默认是#user nobody;是注释的,linux下改成user root; macos下改成user 用户名 所在组; 然后重新加载配置文件就可以了, 用户名可以通过who am i 命令来查看。

Nginx配置高可用的集群(了解)

什么是高可用

1、需要的环境

(1)需要两台 nginx 服务器
(2)需要 keepalived
(3)需要虚拟 ip

2、配置高可用的准备工作
(1)需要两台服务器 192.168.17.129 和 192.168.17.131
(2)在两台服务器安装 nginx
(3)在两台服务器安装 keepalived

3、在两台服务器安装 keepalived
(1)使用 yum 命令进行安装
yum install keepalived –y

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MblPApP9-1682169922550)(null)]

(2)安装之后,在 etc 里面生成目录 keepalived,有文件 keepalived.conf

4、完成高可用配置(主从配置)
(1)修改/etc/keepalived/keepalivec.conf 配置文件

global_defs {notification_email {acassen@firewall.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.locsmtp_server 192.168.17.129smtp_connect_timeout 30router_id LVS_DEVEL
}
vrrp_script chk_http_port {script "/usr/local/src/nginx_check.sh"interval 2 #(检测脚本执行的间隔)weight 2
}
vrrp_instance VI_1 {state BACKUP # 备份服务器上将 MASTER 改为 BACKUP interface ens33 //网卡virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同priority 90 # 主、备机取不同的优先级,主机值较大,备份机值较小advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.17.50 // VRRP H 虚拟地址} }

(2)在/usr/local/src 添加检测脚本

#!/bin/bash
A=`ps -C nginx –no-header |wc -l`
if [ $A -eq 0 ];then/usr/local/nginx/sbin/nginxsleep 2if [ `ps -C nginx --no-header |wc -l` -eq 0 ];thenkillall keepalivedfi
fi

(3)把两台服务器上 nginx 和 keepalived 启动
启动 nginx:./nginx

​ 启动 keepalived:systemctl start keepalived.service

5、最终测试
(1)在浏览器地址栏输入 虚拟 ip 地址 192.168.17.50

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WKqnpZH0-1682169921050)(null)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5vllLbV1-1682169917295)(https://cdn.jsdelivr.net/gh/CodeFarmer1999/img_cloud@master/img/20200703193719aaaa.png)]

(2)把主服务器(192.168.17.129)nginx 和 keepalived 停止,再输入 192.168.17.50

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7gyjwbRv-1682169922795)(null)]

Nginx的原理

1、mater 和 worker

2、worker如何进行工作的

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VuEvs2st-1682169922629)(null)]

3、一个 master 和多个 woker 有好处

(1)可以使用 nginx –s reload 热部署,利用 nginx 进行热部署操作
(2)每个 woker 是独立的进程,如果有其中的一个 woker 出现问题,其他 woker 独立的,
继续进行争抢,实现请求过程,不会造成服务中断

4、设置多少个 woker 合适

worker 数和服务器的 cpu 数相等是最为适宜的。

5、连接数 worker_connection

第一个:发送请求,占用了 woker 的几个连接数?
答案:2 或者 4 个
第二个:nginx 有一个 master,有四个 woker,每个 woker 支持最大的连接数 1024,支持的最大并发数是多少?

  • 普通的静态访问最大并发数是: worker_connections * worker_processes /2。
  • 而如果是 HTTP 作 为反向代理来说,最大并发数量应该是 worker_connections *
    worker_processes/4。

附录

转发websocket

http {map $http_upgrade $connection_upgrade {default upgrade;'' close;}upstream websocket {server 192.168.100.10:8010;}server {listen 80;location / {proxy_pass http://websocket;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection $connection_upgrade;proxy_set_header Host $host;}}
}# 另一种配置(只配置location),例子中是通过sockJS发送的连接)
location /chat/ {proxy_pass http://127.0.0.1:13333;proxy_http_version 1.1;# ip相关设置proxy_set_header  Host $host;proxy_set_header  X-Real-IP  $remote_addr;proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;# 升级为websocket协议proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";}

官网说明:https://www.nginx.com/blog/websocket-nginx/

升级协议时可以不设置变量,直接将Upgrade设置为 “websocket” ,将Connection设置为"upgrade"也行

  • 还包不包含代理的ip呢?X-Forwarded-For
    • 每次是追加前一个代理的ip。见http的笔记。
  • 如果不追加X-Forwarded-For,会自动追加么?

解决方案一

 其实只要配置nginx.conf的对应localhost里面的这几个参数就好

\\1. proxy_connect_timeout;
\\2. proxy_read_timeout; 服务器对你等待的最大时间
\\3. proxy_send_timeout;

   		# 若超时,配置proxy_connect_timeout 4s; #配置点1proxy_read_timeout 60s; #配置点2,如果没效,可以考虑这个时间配置长一点proxy_send_timeout 12s; #配置点3

静态资源过滤

location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf|css|js|eot|svg|ttf|woff|woff2|properties|json)$ {proxy_pass http://127.0.0.1:8080;sendfile on;gzip_http_version 1.1;gzip_comp_level 9;gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png;
}

使用变量/指令等

set

可以将常用的路径通过set指令设置为变量,语法为:

set 变量名值;引用使用变量名值;引用使用变量名;

例子:

set $doc_root /usr/local/var/www;

变量常以$开头,和linux规则一样。

map

map $var1 $var2 {...}

匹配变量1( v a r 1 )的值来构造或改变变量 2 ( var1)的值来构造或改变变量2( var1)的值来构造或改变变量2var2)的内容。

常见变量1 :

  • $args 是nginx内置变量,就是获取的请求 url 的参数
  • $http_upgrade 内置变量,HTTP Header中Upgrade的值

举个栗子:“转发websocket”:

    map $http_upgrade $connection_upgrade {default upgrade;'' close;}

如果HTTP Header中Upgrade的内容为空,就将$connection_upgrade设为close;

如果Upgrade没有匹配到对应内容,则用default将$connection_upgrade设为upgrade。

注:

  • 不要将map写在server块中
  • 匹配到就执行,没匹配到就走default,有点儿像编程语言中switch语句的用法,不过不用自己加break了。
  • 可以理解为,对变量1和变量2做“映射”,设置每种变量1 的值为key(第一列),一 一对应的value写在第二页。

酌情优化

sendfile

Nginx开启sendfile配置来提高文件的传输速率。

http {
...sendfile on
...
}

大多数sendfile配置开启后,Nginx在进行数据传输,会调用sendfile()函数, Linux 2.0+ 以后的推出的一个系统调用。对比一般的数据的网络传输sendfile会有更少的切换和更少的数据拷贝。
https://www.jianshu.com/p/6aa4cc5336e2

gzip

缓存

https代理-安装SSL模块

Nginx配置https代理,一直报错

nginx: [emerg] https protocol requires SSL support in /usr/local/nginx/conf/nginx.conf:49

这个主要原生是因为nginx没有安装ssl模块

执行步骤

[root@120 ~]# cd /usr/local/src/nginx-1.6.1
configure arguments: --prefix=/usr/local/nginx
[root@120 nginx-1.16.1]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module
[root@120 nginx-1.16.1]# make[root@120 nginx-1.16.1]# cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
[root@120 nginx-1.16.1]# cp ./objs/nginx /usr/local/nginx/sbin/
cp:是否覆盖"/usr/local/nginx/sbin/nginx"? y如果提示:cp: 无法创建普通文件"/usr/local/nginx/sbin/nginx": 文本文件忙
先把nginx停止
[root@120 nginx-1.16.1]# /usr/local/nginx/sbin/nginx -s quit
然后启动
[root@120 nginx-1.16.1]# /usr/local/nginx/sbin/nginx

复制

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

安装模块后只是能转发https代理了,由于还没有安装ssl证书,做https服务器还是会报错。

也就是以http协议访问代理服务器,可以被转发到https协议的url上;但还无法用https协议访问代理服务器

我们来到Nginx安装目录下,来查看是否有安装ssl模块成功。执行./sbin/nginx -V即可看到如下图:

configure arguments: --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --pid-path=/usr/local/nginx/conf/nginx.pid --lock-path=/usr/local/nginx/lock/nginx.lock --with-http_ssl_module

记得开放443防火墙、安全组端口

错误记录

403

  • 以后的推出的一个系统调用。对比一般的数据的网络传输sendfile会有更少的切换和更少的数据拷贝。
    https://www.jianshu.com/p/6aa4cc5336e2

gzip

缓存

https代理-安装SSL模块

Nginx配置https代理,一直报错

nginx: [emerg] https protocol requires SSL support in /usr/local/nginx/conf/nginx.conf:49

这个主要原生是因为nginx没有安装ssl模块

执行步骤

[root@120 ~]# cd /usr/local/src/nginx-1.6.1
configure arguments: --prefix=/usr/local/nginx
[root@120 nginx-1.16.1]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module
[root@120 nginx-1.16.1]# make[root@120 nginx-1.16.1]# cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
[root@120 nginx-1.16.1]# cp ./objs/nginx /usr/local/nginx/sbin/
cp:是否覆盖"/usr/local/nginx/sbin/nginx"? y如果提示:cp: 无法创建普通文件"/usr/local/nginx/sbin/nginx": 文本文件忙
先把nginx停止
[root@120 nginx-1.16.1]# /usr/local/nginx/sbin/nginx -s quit
然后启动
[root@120 nginx-1.16.1]# /usr/local/nginx/sbin/nginx

复制

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

安装模块后只是能转发https代理了,由于还没有安装ssl证书,做https服务器还是会报错。

也就是以http协议访问代理服务器,可以被转发到https协议的url上;但还无法用https协议访问代理服务器

我们来到Nginx安装目录下,来查看是否有安装ssl模块成功。执行./sbin/nginx -V即可看到如下图:

configure arguments: --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --pid-path=/usr/local/nginx/conf/nginx.pid --lock-path=/usr/local/nginx/lock/nginx.lock --with-http_ssl_module

记得开放443防火墙、安全组端口

错误记录

403

注意:如果访问图片出现403 Forbidden错误,可能是因为nginx.conf 的第一行user配置不对,默认是#user nobody;是注释的,linux下改成user root; macos下改成user 用户名 所在组; 然后重新加载配置文件或者重启,再试一下就可以了, 用户名可以通过who am i 命令来查看。

歌词下载