阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Nginx高级应用–负载均衡与rewrite规则

163次阅读
没有评论

共计 5947 个字符,预计需要花费 15 分钟才能阅读完成。

Nginx 除了可以用作 web 服务器外,他还可以用来做高性能的反向代理服务器,它能提供稳定高效的负载均衡解决方案。nginx 可以用轮询、IP 哈希、URL 哈希等方式调度后端服务器,同时也能提供健康检查功能。目前有众多公司均已经部署使用 nginx 实现基于七层的负载均衡功能。

一、Nginx 负载均衡

为了实现 Nginx 的反向代理以及负载均衡功能,应用中需要用到两个模块,HttpProxyModule 和 HttpUpstreamModule 模块;其中 HttpProxyModule 模块的作用是将用户的数据请求转发到其他服务器上,HttpUpstreamModule 模块是提供负载均衡技术。

Nginx 目前提供的负载均衡算法:

ngx_http_upstream_round_robin,加权轮询,可均分请求,是默认算法,集成在框架中。

ngx_http_upstream_ip_hash_module,IP 哈希,可保持会话。

ngx_http_upstream_least_conn_module,最少连接数,可均分连接。

ngx_http_upstream_hash_module,一致性哈希,可减少缓存数据的失效

负载均衡实现原理拓扑图(多层负载)

Nginx 高级应用 -- 负载均衡与 rewrite 规则

Nginx 反向代理模块配置方法示例解析

示例:

location ~* \.(mp3|mp4)$ {#匹配 URL 以 MP3 或者 MP4 结尾的请求

    proxy_pass http://localhost:8080        #转发到本机 8080 端口

}

location / {#匹配任意 URL

    proxy_pass http://localhost:8081  #转发到本机 8081 端口

        proxy_set_header    X-Forwarded-For    $remote_addr    #保留用户真实 IP

}

location 指令可以直接匹配字符串,也可以进行正则表达式匹配

~ 表示区分大小写,~* 表示不区分大小写匹配,= 表示精确匹配

proxy_pass 指令可以根据 location 匹配的情况建立前后端的代理映射关系

X-Forwarded-For 用于实现定义数据包头,记录用户真实 IP

Nginx 负载均衡模块配置方法示例解析

http {

upstream backend {

ip_hash;

server web1.test.com weight 1;

server web2.test.com weight 2;

server web3.test.com ;

}

server {

listen 80;

server_name web.test.com;

location / {

proxy_pass http://backend;

}}}

upstream 定义后端服务器集合,backend 是服务器组名

proxy-pass 和 fastcgi_pass 将请求转发给一组服务器

ip_hash 可以根据用户 ip 地址的 hash 值分配固定的后端服务器

二、Nginx 负载均衡案例

服务器名称网路配置
nginx.test.cometh0:122.126.152.183
eth1:192.168.1.2
web1.test.comeht0:192.168.1.3
web2.test.cometh0:192.168.1.4
web3.test.cometh0:192.168.1.5

3 台 web 机器配置

在 web1 web2 web3 上安装 httpd 并配置网卡

vim /etc/sysconfig/network-scripts/ifcfg-eth0

DEVICE=eth0

BOOTPROTO=static

IPADDR=192.168.1.3

NETMASK=255.255.255.0

GATEWAY=192.168.1.2

ONBOOT=yes

TYPE=Ethernet

service network restart

yum install -y httpd

iptables -F

iptables -X

service iptables save

setenforce 0

sed -i s/enforcing/disabled/g /etc/sysconfig/selinux

echo “web1  192.168.1.3” > /var/www/html/index.html

service httpd restart

chkconfig httpd on

web2 web3 机器上执行与 web1 相同步骤,注意修改部分参数

Nginx 代理服务器设置

vim /etc/sysconfig/network-scripts/ifcfg-eth0

DEVICE=eth0

BOOTPROTO=static

IPADDR=122.126.152.183

NETMASK=255.255.255.0

GATEWAY=122.126.152.0

ONBOOT=yes

TYPE=Ethernet

vim /etc/sysconfig/network-scripts/ifcfg-eth1

DEVICE=eth1

BOOTPROTO=static

IPADDR=192.168.1.2

NETMASK=255.255.255.0

GATEWAY=192.168.1.1

ONBOOT=yes

TYPE=Ethernet

service network restart

iptables -F

iptables -X

service iptables save

setenforce 0

sed -i s/enforcing/disabled/g /etc/sysconfig/selinux

wget http://nginx.org/download/nginx-1.6.3.tar.gz

tar zxf nginx-1.6.3.tar.gz -C /usr/src/

yum install gcc pcre pcre-devel openssl openssl-devel gd gd-devel perl perl-ExtUtils-Embed

cd /usr/src/nginx-1.6.3/

./configure –prefix=/usr/local/nginx \

–with-ipv6 \

–with-http_ssl_module \

–with-http_realip_module \

–with-http_addition_module \

–with-http_dav_module \

–with-http_gzip_static_module \

–with-http_perl_module \

–with-mail_ssl_module

make && make install

修改配置文件

vim /usr/local/nginx/conf/nginx.conf

user    nobody;

worker_processes    1;

error_log    logs/error.log    notice;

pid    logs/nginx.pid;

events    {

worker_connections    5024;

}

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” ‘;

sendfile    on;

tcp_nopush    on;

server_tokens    off;

keepalive_timeout    65;

keepalive_requests    100;

gzip    on;                                    #开启压缩

gzip_min_length    1000;                #小于 1000B 内容不压缩

gzip_buffers    16    32k;                #压缩缓存的个数和容量

gzip_types    text/plain    application/xml;        #指定压缩文件类型

gzip_comp_level    2;#压缩级别为 2,数字越大压缩效果越好

client_body_buffer_size    128k;#允许客户端请求缓存大小

client_max_body_size    100m;                            #允许请求的最大文件容量

large-client_header_buffers    4    8k;#

proxy_buffering    on;                                          #开启代理缓冲功能

proxy_buffer_size    8k;                                        #第一部分响应数据的缓存大小

proxy_buffers    8    128k;                                    #响应数据的缓存个数和容量

proxy_cache_path    /usr/local/nginx/cache    levels=1:2    keys_zone=one:100m    inactive=1d    max_size=2G;   

# 设置缓存目录,levels 设置缓存个数,keys_zone 定义缓存名字和容量,inactive 定义缓存存活时间,max_size 定义硬盘的缓存容量

proxy_connect_timeout    60s;            #与后端服务器建立 TCP 连接握手超时时间

upstream servers {

#ip_hash;iphash 确保相同客户端 ip 使用相同的后端服务器,不适用就默认轮询

server    192.168.1.3:80    max_fails=3    fail_timeout=30s    weight=2;

server    192.168.1.4:80    max_fails=3    fail_timeout=30s    weight=2;

server    192.168.1.5:80    max_fails=3    fail_timeout=30s    weight=2;

}

server {

    listen    80;

    server_name    web.test.com;

    access_log    logs/host.access.log    main;

    location / {

proxy_pass http://servers;

proxy_cache one;

proxy_set_header X-Forwarded-For $remote_addr;

    }

}}

配置完成执行

echo “/usr/local/nginx/sbin/nginx” >> /etc/rc.local

浏览器访问 192.168.1.2 或者 122.126.152.183 刷新将分别得到不同的 web 页面信息

三、Nginx rewrite 规则

nginx 的 rewrite 语法格式和 apache 非常相似,rewrite regex replacement [flag], 其中 flag 可以被设置为 last 结束当前指令并重新搜索 location 匹配、break 结束当前 rewrite 指令、redirect 临时重定向 302、permanent 永久重定向 301。

rewrite 地址重写及 return 应用的语法解析:

## 根据浏览器标识,访问资源重定向到指定文件目录, 下面用 IE 浏览器示例

if ($http_user_agent ~ MSIE) {

rewrite ^(.*)$ /msie/$1 break;

}

## 将��动客户端的请求重定向到其他服务器

if    ($http_user_agent ~* ‘(iphone|ipod)’ )  {

rewrite    ^.+    http://mobile.site.com$uri;

}

## 用户使用 POST 方式请求数据时候,返回 405

if ($request_method = POST) {

return 405;

}

rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;

rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra last;

## 访问 admin 时候重定向到 admin 目录

location /php_admin {

rewrite ^/php_admin/.*$ /admin permanent;

}

下面关于 Nginx 的文章您也可能喜欢,不妨参考下:

CentOS 7.2 下编译安装 PHP7.0.10+MySQL5.7.14+Nginx1.10.1  http://www.linuxidc.com/Linux/2016-09/134804.htm

搭建基于 Linux6.3+Nginx1.2+PHP5+MySQL5.5 的 Web 服务器全过程 http://www.linuxidc.com/Linux/2013-09/89692.htm

CentOS 6.3 下 Nginx 性能调优 http://www.linuxidc.com/Linux/2013-09/89656.htm

CentOS 6.3 下配置 Nginx 加载 ngx_pagespeed 模块 http://www.linuxidc.com/Linux/2013-09/89657.htm

CentOS 6.4 安装配置 Nginx+Pcre+php-fpm http://www.linuxidc.com/Linux/2013-08/88984.htm

Nginx 安装配置使用详细笔记 http://www.linuxidc.com/Linux/2014-07/104499.htm

Nginx 日志过滤 使用 ngx_log_if 不记录特定日志 http://www.linuxidc.com/Linux/2014-07/104686.htm

Nginx 的 500,502,504 错误解决方法 http://www.linuxidc.com/Linux/2015-03/115507.htm

CentOS 7 编译安装 Nginx1.10.2 脚本启动失败解决思路 http://www.linuxidc.com/Linux/2017-01/139794.htm

Nginx 的详细介绍:请点这里
Nginx 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-02/140476.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-21发表,共计5947字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中