nginx

第一章 Nginx简介

1.1 Nginx 概述

Nginx (“engine x”) 是一个高性能的 HTTP 和反向代理服务器,特点是占有内存少,并发能 力强,事实上 nginx 的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用 nginx 网站用户有:百度、京东、新浪、网易、腾讯、淘宝等

1.2 Nginx 作为 web 服务器

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

1.3 正向代理

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

1.4 反向代理

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

1.5 负载均衡

客户端发送多个请求到服务器,服务器处理请求,有一些可能要与数据库进行交互,服 务器处理完毕后,再将结果返回给客户端。 这种架构模式对于早期的系统相对单一,并发请求相对较少的情况下是比较适合的,成 本也低。但是随着信息数量的不断增长,访问量和数据量的飞速增长,以及系统业务的复杂 度增加,这种架构会造成服务器相应客户端的请求日益缓慢,并发量特别大的时候,还容易 造成服务器直接崩溃。很明显这是由于服务器性能的瓶颈造成的问题,那么如何解决这种情 况呢? 我们首先想到的可能是升级服务器的配置,比如提高 CPU 执行频率,加大内存等提高机 器的物理性能来解决此问题,但是我们知道摩尔定律的日益失效,硬件的性能提升已经不能 满足日益提升的需求了。最明显的一个例子,天猫双十一当天,某个热销商品的瞬时访问量 是极其庞大的,那么类似上面的系统架构,将机器都增加到现有的顶级物理配置,都是不能 够满足需求的。那么怎么办呢? 上面的分析我们去掉了增加服务器物理配置来解决问题的办法,也就是说纵向解决问题 的办法行不通了,那么横向增加服务器的数量呢?这时候集群的概念产生了,单个服务器解 决不了,我们增加服务器的数量,然后将请求分发到各个服务器上,将原先请求集中到单个服务器上的情况改为将请求分发到多个服务器上,将负载分发到不同的服务器,也就是我们 所说的负载均衡

1.6 动静分离

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

第二章 Nginx安装

2.1 在linux系统中的安装

1.官网下载

http://nginx.org/en/download.html

解压完成后直接进入解压目录下 运行 ./configure 文件

2.make 下

3.再接着 make install 安装完成

4.可以通过whereis nginx 查找安装位置,安装完毕会生成一个nginx文件夹


错误信息:

./configure: error: the HTTP rewrite module requires the PCRE library.

解决方法:安装pcre-devel

yum install pcre-devel
错误信息:

./configure: error: the HTTP gzip module requires the zlib library.

解决方法:安装zlib-devel

yum install zlib-devel

过程中可能会出现make: *** No rule to make target build', needed bydefault’. Stop.错误

需要安装openssl以及ncurses组件

yum install -y openssl*

yum -y install ncurses-devel

checking for C compiler … not found ./configure: error: C compiler cc is not found

yum install glibc-devel

Linux 开放端口号 CentOS中测试

查看 firewalld 状态

systemctl status firewalld

开放端口3306: success

// --permanent 永久生效,没有此参数重启后失效

重新加载:success

firewall-cmd --reload

查看端口号是否开启: yes/no

firewall-cmd --zone=public --query-port=3306/tcp

删除端口号:success   需要重新加载  
firewall-cmd --zone=public --remove-port=3306/tcp --permanent

2.2 在windows系统中的安装

下载后解压就能用

第 3 章 nginx 常用的命令和配置文件

3.1 nginx 常用的命令:

linux系统

cd /usr/local/nginx/sbin/ ./nginx 启动 ./nginx -s stop 停止 ./nginx -s quit 安全退出 ./nginx -s reload 重新加载配置文件 ps aux|grep nginx

3.2 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;

#log_format main '$remote_addr - r e m o t e u s e r [ remote_user [ remoteuser[time_local] “$request” ’

'$status b o d y b y t e s s e n t " body_bytes_sent " bodybytessent"http_referer" ’

‘“ h t t p u s e r a g e n t " " http_user_agent" " httpuseragent""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 8443;
server_name localhost;

#charset koi8-r;

#access_log logs/host.access.log main;

location /oneblog/ {
root /;
rewrite ^/oneblog/(.*)$ /oneblog/oneblog/$1 break;
}

#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;
}

proxy the PHP scripts to Apache listening on 127.0.0.1:80

#location ~ .php$ {

proxy_pass http://127.0.0.1;

#}

pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

#location ~ .php$ {

root html;

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;

include fastcgi_params;

#}

deny access to .htaccess files, if Apache’s document root

concurs with nginx’s one

#location ~ /.ht {

deny all;

#}
}

another virtual host using mix of IP-, name-, and port-based configuration

#server {

listen 8000;

listen somename:8080;

server_name somename alias another.alias;

location / {

root html;

index index.html index.htm;

}

#}

HTTPS server

#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;

}

#}

}

3.2.1第一部分:全局块

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

比如

worker_processes 1;

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

3.2.2第二部分:evernts块

比如上面的配置

events { worker_connections 1024; }

events 块涉及的指令主要影响 Nginx 服务器与用户的网络连接,常用的设置包括是否开启对多 work process 下的网络连接进行序列化,是否允许同时接收多个网络连接,选取哪种事件驱动模型来处理连接请求,每个 word process 可以同时支持的最大连接数等。 上述例子就表示每个 work process 支持的最大连接数为 1024. 这部分的配置对 Nginx 的性能影响较大,在实际中应该灵活配置。

3.2.3第三部分:http块

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

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

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

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

而每个 server 块也分为全局 server 块,以及可以同时包含多个 locaton 块。
1、全局 server 块
最常见的配置是本虚拟机主机的监听配置和本虚拟主机的名称或 IP 配置。
2、location 块
一个 server 块可以配置多个 location 块。
这块的主要作用是基于 Nginx 服务器接收到的请求字符串(例如 server_name/uri-string),对虚拟主机名称
(也可以是 IP 别名)之外的字符串(例如 前面的 /uri-string)进行匹配,对特定的请求进行处理。地址定向、数据缓
存和应答控制等功能,还有许多第三方模块的配置也在这里进行。

第 4 章 nginx 配置实例-反向代理

4.1 反向代理实例一

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

第一步修改电脑上的配置文件:

C:\Windows\System32\drivrs\etc
47.94.243.187 www.123.com

第二步

第三步

4.3 反向代理实例二

实现效果:使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务中 nginx 监听端口为 9113 访问 http://127.0.0.1:9113/admintest1 直接跳转到 127.0.0.1:8111

访问 http://127.0.0.1:9113/admintest2 直接跳转到 127.0.0.1:8085

server {
listen 9113;
server_name 47.94.243.187;

#charset koi8-r;

#access_log logs/host.access.log main;

location ~ /admintest1 {
root html;
index index.html index.htm;
proxy_pass http://127.0.0.1:8111;
}

location ~ /admintest2 {
root html;
index index.html index.htm;
proxy_pass http://127.0.0.1:8085;
}

#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;
}

proxy the PHP scripts to Apache listening on 127.0.0.1:80

#location ~ .php$ {

proxy_pass http://127.0.0.1;

#}

pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

#location ~ .php$ {

root html;

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;

include fastcgi_params;

#}

deny access to .htaccess files, if Apache’s document root

concurs with nginx’s one

#location ~ /.ht {

deny all;

#}
}

location 指令说明 该指令用于匹配

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

第 5 章 nginx 配置实例-负载均衡

随着互联网信息的爆炸性增长,负载均衡(load balance)已经不再是一个很陌生的话题, 顾名思义,负载均衡即是将负载分摊到不同的服务单元,既保证服务的可用性,又保证响应 足够快,给用户很好的体验。快速增长的访问量和数据流量催生了各式各样的负载均衡产品, 很多专业的负载均衡硬件提供了很好的功能,但却价格不菲,这使得负载均衡软件大受欢迎, nginx 就是其中的一个,在 linux 下有 Nginx、LVS、Haproxy 等等服务可以提供负载均衡服 务,而且 Nginx 提供了几种分配方式(策略): 

实现效果:配置负载均衡

5种方式

1、轮询(默认)

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

upstream backserver {
server 47.94.243.187;
server 47.94.243.187;
}

2、指定权重
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。

upstream backserver { server 47.94.243.187weight=3; server 47.94.243.187weight=5; }

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

upstream backserver { ip_hash; server 47.94.243.187; server 47.94.243.187; }

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

upstream backserver { server server1; server server2; fair; }

5、url_hash(第三方)
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。

upstream backserver { server squid1:3128; server squid2:3128; hash $request_uri; hash_method crc32; }

在需要使用负载均衡的http下增加

proxy_pass http://backserver/; 
upstream backserver{ 
ip_hash; 
server 127.0.0.1:8383 down; (down 表示当前的server暂时不参与负载) 
server 127.0.0.1:8181 weight=2; (weight 默认为1.weight越大,负载的权重就越大) 
server 127.0.0.1:8090; 
server 127.0.0.1:7070 backup; (其它所有的非backup机器down或者忙的时候,请求backup机器) 
}

max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误 
fail_timeout:max_fails次失败后,暂停的时间

第 6 章 nginx 配置实例-动静分离

Nginx 动静分离简单来说就是把动态跟静态请求分开,不能理解成只是单纯的把动态页面和
静态页面物理分离。严格意义上说应该是动态请求跟静态请求分开,可以理解成使用 Nginx
处理静态页面,Tomcat 处理动态页面。动静分离从目前实现角度来讲大致分为两种,
一种是纯粹把静态文件独立成单独的域名,放在独立的服务器上,也是目前主流推崇的方案;
另外一种方法就是动态跟静态文件混合在一起发布,通过 nginx 来分开。
通过 location 指定不同的后缀名实现不同的请求转发。通过 expires 参数设置,可以使
浏览器缓存过期时间,减少与服务器之前的请求和流量。具体 Expires 定义:是给一个资
源设定一个过期时间,也就是说无需去服务端验证,直接通过浏览器自身确认是否过期即可,
所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件,
不建议使用 Expires 来缓存),我这里设置 3d,表示在这 3 天之内访问这个 URL,发送
一个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码
304,如果有修改,则直接从服务器重新下载,返回状态码 200。

示例

autoindex on 表示是否会列出目录,就是说不访问该路径下的具体文件,可以展示出该文件夹下有多少文件

示例二

location /oneblog/ {
root /;
rewrite ^/oneblog/(.*)$ /usr/local/images/oneblog/$1 break;
}

#通过访问sunjian.ltd/oneblog/xxx.jpg可以访问到具体的文件

最后检查 Nginx 配置是否正确即可,然后测试动静分离是否成功,之需要删除后端 tomcat 服务器上的某个静态文件,查看是否能访问,如果可以访问说明静态资源 nginx 直接返回 了,不走后端 tomcat 服务器

第七章 Nginx 配置高可用的集群

Keepalived+Nginx 高可用集群(主从模式)

1、准备工作

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

2、配置高可用的准备工作

(1)需要两台服务器 192.168.169.130 和 192.168.169.128 47.94.243.187

(2)在两台服务器安装 nginx

3、在两台服务器安装 keepalived

(1)任意文件夹下使用 yum 命令进行安装 yum install keepalived –y

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

4、完成高可用配置(主从配置)

(1)主服务器修改/etc/keepalived/keepalivec.conf 配置文件以及在主服务器中文件夹/usr/local/src 添加检测脚本nginx_check.sh

主服务器修改/etc/keepalived/keepalivec.conf 配置文件

global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.169.130
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_http_port {
script “/usr/local/src/nginx_check.sh”
interval 2 #(检测脚本执行的间隔)
weight 2
}
vrrp_instance VI_1 {
state MASTER # 备份服务器上将 MASTER 改为 BACKUP
interface ens32 //网卡
virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
priority 100 # 主、备机取不同的优先级,主机值较大,备份机值较小
advert_int 1

authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.169.125 // VRRP H 虚拟地址
}
}

主服务器ip地址

在主服务器文件夹中/usr/local/src 添加检测脚本nginx_check.sh

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

(2)从服务器修改/etc/keepalived/keepalivec.conf 配置文件以及在从服务器中文件夹/usr/local/src 添加检测脚本

从服务器修改/etc/keepalived/keepalivec.conf 配置文件

global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.169.130
smtp_connect_timeout 30
router_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 ens32 //网卡
virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
priority 90 # 主、备机取不同的优先级,主机值较大,备份机值较小
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.169.125 // VRRP H 虚拟地址
}
}

从服务器ip地址

在从服务器文件夹中/usr/local/src 添加检测脚本nginx_check.sh

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

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

通过ip a查看是否有有相应的配置,没有则配置无效

(4)测试

在浏览器地址栏输入 虚拟 ip 地址 192.168.169.125 // VRRP H 虚拟地址

(2)把主服务器(192.168.169.130)nginx 和 keepalived 停止,再输入 192.168.169.125 ,访问成功,配置成功

/etc/keepalived/keepalivec.conf 原文件

三大部分

  1. global_defs 全局定义
  2. vrrp_script chk_http_port 可执行脚本
  3. vrrp_instance VI_1 虚拟ip的配置

! 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
router_id LVS_DEVEL
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}

vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.16
192.168.200.17
192.168.200.18
}
}

virtual_server 192.168.200.100 443 {
delay_loop 6
lb_algo rr
lb_kind NAT
persistence_timeout 50
protocol TCP

real_server 192.168.201.100 443 {
weight 1
SSL_GET {
url {
path /
digest ff20ad2481f97b1754ef3e12ecd3a9cc
}
url {
path /mrtg/
digest 9b3a0c85a887a256d6939da88aabd8cd
}
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}
}

virtual_server 10.10.10.2 1358 {
delay_loop 6
lb_algo rr
lb_kind NAT
persistence_timeout 50
protocol TCP

sorry_server 192.168.200.200 1358

real_server 192.168.200.2 1358 {
weight 1
HTTP_GET {
url {
path /testurl/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
url {
path /testurl2/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
url {
path /testurl3/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}

real_server 192.168.200.3 1358 {
weight 1
HTTP_GET {
url {
path /testurl/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334c
}
url {
path /testurl2/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334c
}
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}
}

virtual_server 10.10.10.3 1358 {
delay_loop 3
lb_algo rr
lb_kind NAT
persistence_timeout 50
protocol TCP

real_server 192.168.200.4 1358 {
weight 1
HTTP_GET {
url {
path /testurl/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
url {
path /testurl2/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
url {
path /testurl3/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}

real_server 192.168.200.5 1358 {
weight 1
HTTP_GET {
url {
path /testurl/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
url {
path /testurl2/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
url {
path /testurl3/test.jsp
digest 640205b7b0fc66c1ea91c463fac6334d
}
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}
}

小插曲
阿里云上如何配置多个站点
https://jingyan.baidu.com/article/f96699bb77fd14c94f3c1b6d.html
https://help.aliyun.com/document_detail/171730.html?spm=5176.22414175.sslink.3.7bfa777cOdqvj2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值