Nginx反向代理与负载均衡

本文详细介绍了如何在Nginx中配置反向代理和负载均衡,包括使用`proxy_pass`指令、调整连接超时时间、以及对不同路径的处理。还探讨了配置有效性检查和HTTP协议的三次握手概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过反向代理或负载均衡,可实现阻塞网络的接通和负载均衡(_)

编辑nginx配置文件:vim nginx.conf

1、反向代理

server {
	listen 8090;
	server_name syslog_server;	
	
	location /yz_es_syslog_ipf/ {
		proxy_pass http://173.*.*.*:9200;
		proxy_redirect off;
		proxy_set_header Host $host;
		proxy_set_header X_Real-IP $Remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
	}
}

注意,这里转发请求时保留原来路径,即:
http://132...:8090/yz_es_syslog_ipf/ipf_alarm_v1_/_search?pretty --> http://173...:9200/yz_es_syslog_ipf/ipf_alarm_v1_/_search?pretty

server {
	listen 8090;
	server_name syslog_server;
	
	location /yz_es_syslog_ipf/ {
		proxy_pass http://173.*.*.*:9200/;
		proxy_redirect off;
		proxy_set_header Host $host;
		proxy_set_header X_Real-IP $Remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
	}	
}

注意,这里转发请求时去除原来路径,即:
http://132...:8090/yz_es_syslog_ipf/ipf_alarm_v1_/_search?pretty -->
http://173...:9200/ipf_alarm_v1_/_search?pretty

说明:这里的表述比较简单,关于反向代理的详细阐述,参见本文第四部分的nginx.conf示例

2、负载均衡

upstream gateway {
    server 172.*.*.1:8081 weight=1 max_fails=2 fail_timeout=30s;
	server 172.*.*.2:8081 weight=1 max_fails=2 fail_timeout=30s;
	server 172.*.*.3:8081 weight=1 max_fails=2 fail_timeout=30s;
    server 172.*.*.4:8081 weight=1 max_fails=2 fail_timeout=30s;
    server 172.*.*.5:8081 weight=1 max_fails=2 fail_timeout=30s;
}

### 虚拟服务
server {
    listen       80;
    server_name  localhost;
    error_page  404  /404.html;
    error_page  504  /50x.html;
    error_page  413  /413.html;
    error_page  400  /400.html;
    error_page  502  /50x.html;

	## 读取请求体的时限,连接建立后,nginx接收请求body,超时则返回给客服端408(request time out)
    # client_body_timeout 1000;
    ## 发送响应的时限,服务端向客户端发送数据包,规定时间内客户端没收到,则超时
    # send_timeout 1000;
    ## 保持闲置连接的时限,超过后nginx和客户端(浏览器)都会关闭连接
    # keepalive_timeout 1000;
    
    ## nginx与【被代理服务】建立连接的时限,即发起握手包seq后等待seq+ack响应的超时时间
    proxy_connect_timeout    3;
    ## nginx读取【被代理服务】的数据的时限,即连接成功后读取后端服务器响应的超时时间
    proxy_read_timeout       600;
    ## nginx发送数据给【被代理服务】的时限
    proxy_send_timeout       60;
	
    ### 以/gxpt/开头的路径负载均衡到上游gateway(原路径去除gxpt)
	location ^~/gxpt/ {
        root  html;
        index index.html index.htm;
        proxy_pass http://gateway/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
    }
    ### 以/dataway/开头的路径负载均衡到上游gateway(原路径保留dataway)
	location /dataway/ {
        root  html;
        index index.html index.htm;
        proxy_pass http://gateway/dataway/;
        proxy_set_header http_x_forwarded_for $http_x_forwarded_for;
    }
}

保存修改后重载配置文件即可:nginx -s reload

3、其他

思考:如何查看当前有效配置 ???即保障新增配置是有效的 ???

nginx -t 会检查配置是否有效 !!!

思考:http协议也需要三次握手 ???三次握手不是tcp连接才有的吗 ???
。。。

4、关于Nginx及其反向代理的详细补充

4.1 nginx 通过配置location块,可以实现请求的反向代理、负载均衡、静态资源加载。location 块可以嵌套在 server 块中,也可以嵌套在其他 location 块中。location 块的基本语法如下:

location [=|^~|~|~*|!~|!~*] /uri 或 pattern {
	# 处理指令
}

1.修饰符: =(精确匹配)、^~(前缀匹配)、~(区分大小写的正则表达式匹配)、~*(不区分大小写的正则表达式匹配)、空(前缀匹配)等。

2./uri 或 pattern:用于匹配请求地址的字符串或正则表达式。

1.精确匹配:使用 = 修饰符,当请求URI与指定字符串完全相等时匹配。

location = / {
	# 仅处理根路径 / 的请求
}

2.前缀匹配:使用 ^~ 修饰符,当请求URI的前缀与指定字符串相等时匹配。

location ^~ /api {
	# 处理 /api 及其子路径的请求
}

### http://localhost:8090/api/getById/3 -> http://127.0.0.1:8081/car/getById/3
location ^~ /api {
	proxy_pass http://127.0.0.1:8081/car;
}

3.正则匹配:使用 ~ 或 ~* 修饰符,分别表示区分大小写和不区分大小写的正则表达式匹配。

location ~* \.(jpg|png|gif)$ {
	# 处理所有以 .jpg、.png 或 .gif 结尾的请求
}

### http://domain.com/icon.jpg => /data/nginx/static/assets/icon.jpg
location ~* \.(gif|jpg|jpeg|css|js|ico)$ {
	root /data/nginx/static/assets/;
}

4.前缀匹配:不带修饰符,匹配 URI 的前缀【默认的匹配方式】。

location /api {
	# 处理 /api 及其子路径的请求
}

### http://localhost:8090/api/getById/3 -> http://127.0.0.1:8081/car/getById/3
location /api {
	proxy_pass http://127.0.0.1:8081/car;
}

### http://localhost:8090/api/getById/3 -> http://127.0.0.1:8081/car/getById/3
location /api/ {
	proxy_pass http://127.0.0.1:8081/car/;
}

5.通用匹配:不带修饰符,匹配所有的请求URI。

location = / {
	# 仅处理根路径 / 的请求
}

6.目录匹配:以斜杠 / 结尾的匹配模式,用于匹配特定的目录。

location /images/ {
	# 处理 /images/ 目录下的请求
}

4.2 当有多个 location 块匹配同一个请求时,Nginx 会按照如下优先级确定使用哪个 location 块:

1.检查是否有精确匹配 (=)。

2.检查是否有前缀匹配 (^~)。

3.检查是否有带有正则表达式的匹配 (~ 或 ~*),并使用第一个匹配的规则。

4.使用最长的前缀匹配 (不带修饰符)。

5.使用通用匹配 /

4.3 nginx.conf 配置样例

#user  nobody;

#### 开启业务进程数。根据服务器核数来配置,一般1核对应1个进程
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 {
    ### 引入conf文件夹下的mime.types文件,使浏览器知道识别文件后缀后该如何展示
    include       mime.types;
    ### 如果mime类型没匹配上,默认使用二进制流的方式传输。
    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;

	### 自定义的日志格式
	log_format proxy '[$time_local] '
					 '源地址: $remote_addr '
					 '源用户: $remote_user '
					 '源请求: "$request" '
					 '源cookie: $http_cookie '  
					 '源状态: $status '
					 '发送字节: $bytes_sent '
					 #'接收字节: $bytes_received '
					 '请求耗时: $request_time '
					 '转发地址: $upstream_addr '
					 '转发状态: $upstream_status '
					 '转发耗时: $upstream_response_time';

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    ### 配置一个虚拟主机
    server {
	    
	    ### 虚拟主机监听的端口
        listen       8090;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
		
		### 这里是放置的dist文件夹的地址,浏览器输入:http://localhost:8090/index 会自动打开index.html页面(系统首页) 
		### dist文件夹下的资源也可被访问,如浏览图片:http://localhost:8090/img/biyilogo.7fe38e11.png
		location / {
            root   D:/workspace-idea/dist;
            index  index.html  index.htm;
            try_files $uri $uri/ /index.html; 
        }

        ### Vue 项目打包后的 dist 目录路径【这个待研究】
        # location ~* .(jpg|jpeg|png|gif|css|js|ico)$ {
        #     root   D:/workspace-idea/dist;  
        #     expires 30d;
        # }
	
		###### 基于^~或默认的前缀匹配时的反向代理,即是简单的前缀替换,示例如下 !!!######
		
	    ###### http://【localhost:8090/gxpt/api】/getById/3 -> http://【127.0.0.1:8081/car】/getById/3
		
		# location /gxpt/api {
		# 	
		#   ### 反向代理
		# 	proxy_pass http://127.0.0.1:8081/car;
		# 	
		# 	proxy_set_header Host               $host;
		# 	proxy_set_header X-Real-IP          $remote_addr;
		# 	proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
		# 	proxy_set_header X-Forwarded-Proto  $scheme;
		# 
		# 	### 配置反向代理的日志格式和位置
		# 	access_log logs/proxy_access.log proxy;
		# }
	
        ###### http://【localhost:8090/gxpt/api】/getById/3 -> http://【127.0.0.1:8081/car/】/getById/3
	
		# location /gxpt/api {
		# 	
		#   ### 反向代理
		# 	proxy_pass http://127.0.0.1:8081/car/;
		# 	
		# 	proxy_set_header Host               $host;
		# 	proxy_set_header X-Real-IP          $remote_addr;
		# 	proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
		# 	proxy_set_header X-Forwarded-Proto  $scheme;
		# 
		# 	# 反向代理的日志格式和位置
		# 	access_log logs/proxy_access.log proxy;
		# }
	
		###### http://【localhost:8090/gxpt/api/】getById/3 -> http://【127.0.0.1:8081/car】getById/3
		
		# location /gxpt/api/ {
		# 	
		#   ### 反向代理
		# 	proxy_pass http://127.0.0.1:8081/car;
		# 	
		# 	proxy_set_header Host               $host;
		# 	proxy_set_header X-Real-IP          $remote_addr;
		# 	proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
		# 	proxy_set_header X-Forwarded-Proto  $scheme;
		# 
		# 	# 反向代理的日志格式和位置
		# 	access_log logs/proxy_access.log proxy;
		# }
	
		###### http://【localhost:8090/gxpt/api/】getById/3 -> http://【127.0.0.1:8081/car/】getById/3
		
		# location ^~ /gxpt/api/ {
		#
		# 	### 反向代理
		# 	proxy_pass http://127.0.0.1:8081/car/;
		# 	
		# 	proxy_set_header Host               $host;
		# 	proxy_set_header X-Real-IP          $remote_addr;
		# 	proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
		# 	proxy_set_header X-Forwarded-Proto  $scheme;
		# 
		# 	# 反向代理的日志位置和格式
		# 	access_log logs/proxy_access.log proxy;
		# }
	
		### http://localhost:8090/api/getById/3 -> http://127.0.0.1:8081/car/getById/3
		### location ^~ /api {
		### 	proxy_pass http://127.0.0.1:8081/car;
		### }
	
        #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;
    #    }
    #}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值