对于Nginx我们很多朋友都会认为是常用的WEB引擎。没错,Nginx和Apache是目前使用比较广泛的WEB引擎,但是Nginx还会用于反向代理功能。比如我们会利用Nginx反向代理功能进行主机端和客户机端的分发资源跳转。Nginx可以根据不同的正则匹配,采取不同的转发策略,并且Nginx对返回结果进行错误页跳转,异常判断等。
比如我们在设置负载均衡的时候,可以实现将故障的服务器重新跳转到另外一台服务器,解决服务器的中断问题。Nginx目前拥有三个代理模式,分别是基于IP代理、基于域名代理、基于端口代理。
1、nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
charset utf-8;
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"';
# log_format main 'remote_addr=$remote_addr:$remote_port, http_x_forwarded_for=$http_x_forwarded_for, proxy_add_x_forwarded_for=$proxy_add_x_forwarded_for ';
access_log logs/access_format.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on
# 原始server
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
}
# 引入自定义的server配置
include my-proxy-server.conf;
}
2、my-proxy-server.conf
########################################################################
# 基于端口代理
########################################################################
server {
listen 81;
server_name localhost;
location / {
proxy_pass http://192.168.0.153:9091;
proxy_redirect default;
}
location = /50x.html {
root html;
}
}
server {
listen 82;
server_name localhost;
location / {
proxy_pass http://git.itplh.com;
proxy_redirect default;
}
location = /50x.html {
root html;
}
}
########################################################################
# 基于域名代理 + gitlocal负载均衡
########################################################################
upstream gitlocal{
server 192.168.0.153:9091;
server 192.168.0.154:9091;
server 192.168.0.155:9091;
}
upstream gitbj{
server git.itplh.con;
}
server {
listen 80;
server_name gitlocal.com;
location / {
proxy_pass http://gitlocal;
proxy_redirect default;
}
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name gitbj.com;
location / {
proxy_pass http://gitbj;
proxy_redirect default;
}
location = /50x.html {
root html;
}
}
关于Nginx反代参数我们可以参考。