Nginx负载均衡
需求:
负载均衡服务器A : 192.168.117.14
web服务器1 : 192.168.117.15
web服务器2 : 192.168.117.16
web1页面内容为web1处理请求,web2页面内容为web2处理请求,修改A负载均衡服务器的配置文件,实现负载均衡;
要求117.15分配的权重为2,117.16分配的权重为1
带权重的负载均衡
进入负载均衡服务器:
修改nginx.conf,在http配置段内添加负载均衡配置:
upstream webserver {
server 192.168.117.15:80 weight=2;
server 192.168.117.16:80 weight=1;
}
修改虚拟主机配置文件,修改代理
location / {
proxy_pass http://webserver;
index index.html index.htm;
}
Nginx的rewrite模块
进入192.168.117.15主机:
在/usr/share/nginx/html目录下创建class/121.html,网页内容为“测试redirect”。
进入192.168.117.14主机:
在/usr/share/nginx/html目录下创建course/11/22/course_33.html,网页内容为“rewrite的测试场景”。
编辑虚拟主机文件,在server配置段中添加域名跳转配置:
location / {
root /usr/share/nginx/html;
rewrite ^/course-(\d+)-(\d+)-(\d+)\.html$ /course/$1/$2/course_$3.html redirect;
if ($http_user_agent ~* Chrome) {
rewrite ^/nginx http://192.168.117.15/class/121.html redirect;
}
if (!-f $request_filename) {
rewrite ^/(.*)$ http://www.baidu.com/baidu?wd=$1&tn=monline_dg&ie=utf-8 redirect;
}
index index.html index.htm;
}
浏览器访问192.168.117.14/course-11-22-33.html
访问192.168.117.14/nginx
访问192.168.117.14/你好
应用场景:
1.基于旧,新域名跳转并加目录
将域名http://www.test.com下面的发帖都跳转到http://mail.test.com/abc且域名跳转后保持参数不变
修改虚拟主机文件:
location / {
rewrite ^/bbs/(.*)$ http://mail.test.com/abc/$1 permanent;
}
浏览器访问 http://www.test.com/bbs/index.html
2.基于参数匹配的跳转
浏览器访问:http://www.test.com/100-(100|200)-100.html跳转到http://www.baidu.com页面
修改虚拟主机文件:
location / {
rewrite ^/100-(100|200)-100\.html$ http://www.baidu.com permanent;
}
浏览器访问 http://www.test.com/100-100-100.html或 http://www.test.com/100-200-100.html
3.基于最普通url请求的跳转,访问一个具体的页面跳转到首页
匹配到/abc/跳转到www.test.com首页
修改虚拟主机文件:
location / {
rewrite ^/abc http://www.test.com permanent;
}
浏览器访问http://www.test.com/abc
正向代理
服务器A:192.168.117.14
服务器B:192.168.117.15
编辑服务器A的defualt虚拟主机文件,在location / 部分加入以下内容,拒绝192.168.117.15以外的访问:
if ( $remote_addr !~* "^192\.168\.117\.15" ){
return 403;
}
编辑服务器B的default虚拟主机文件,添加resolver解析,修改代理配置:
resolver 8.8.8.8;
location / {
proxy_pass http://$http_host$request_uri;
}
windows配置代理服务器
浏览器访问服务器A的IP:
反向代理
服务器A:192.168.117.14
创建aaa.com虚拟主机:
server {
listen 8080;
server_name localhost;
location / {
root /usr/share/nginx/aaa.com;
index index.html index.htm;
}
}
编辑服务器default虚拟主机文件,添加代理配置:
location ~ /aaa.html$ {
proxy_pass http://127.0.0.1:8080;
}
浏览器访问192.168.117.14:80/aaa.html: