学习笔记:Nginx配置反向代理

前言

我就是纯记录的,很简单的一个学习贴。

正向代理和反向代理

这里我只简单说下我自己的理解,对错帮我指出一下,谢谢!

正向代理

正向代理就是和客户端是一伙的,就像威屁恩的作用,威屁恩帮你代理指定服务。你用威屁恩去刷推,就是一个正向代理的访问过程。

反向代理

反向代理和服务端是一伙的,比如我在服务端架了一个Nginx web程序,和一个spring boot web程序,spring boot的访问端口是9090。但是我开了防火墙,不允许你直接访问9090。于是我给Nginx配置了90端口,代理到9090,并允许防火墙暴露90端口。那你访问Nginx的90端口,就会自动给你代理到spring boot的9090,这个就是反向代理的访问过程。

准备

写了2个spring boot作为访问示例。很简单的代码,就写了一个Controller作为访问用。

package com.eric.nginx_test_1.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
        return "this is nginx test 1";
    }

}

Nginx配置

这里我暴露了1111和2222端口,分别指向9191和9292的两台spring boot服务。并且配置了404错误页面的指向,当访问到404页面时,分别指向百度和必应的搜索。

http {
	server {
		listen		1111;
		server_name	www.nginx_test_1.com;

		location / {
			proxy_pass	http://127.0.0.1:9191;
		}

		proxy_intercept_errors	on;
		error_page	404	/404.html;
		location /404.html {
			proxy_pass	https://www.baidu.com/s?wd=404;
		}
	}

	server {
		listen		2222;
		server_name	www.nginx_test_2.com;

		location / {
			proxy_pass	http://127.0.0.1:9292;
		}

		proxy_intercept_errors	on;
		error_page	404	/404.html;
		location /404.html {
			proxy_pass	https://cn.bing.com/search?q=404;
		}
	}
}

events {
	worker_connections  1024;
}

启动

启动Spring Boot服务

启动Spring Boot服务的脚本可以参考shell脚本优雅启动SpringBoot项目

启动nginx_test_1

脚本启动nginx_test_1服务

# /usr/mySpringBoot/nginx_test_1/nginx_test_1.sh start
>>> start nginx_test_1-0.0.1-SNAPSHOT.jar successed PID=44653 <<<

curl测试可以访问

# curl http://127.0.0.1:9191/hello
this is nginx test 1

启动nginx_test_2

脚本启动nginx_test_2服务

# /usr/mySpringBoot/nginx_test_2/nginx_test_2.sh start
>>> start nginx_test_2-0.0.1-SNAPSHOT.jar successed PID=44983 <<<

curl测试可以访问

# curl http://127.0.0.1:9292/hello
this is nginx test 2

测试

接下来进行客户端访问测试,这里为了有个比较直观的展示,我用虚拟机外面的这台Windows在浏览器访问url进行测试

首先获取虚拟机IP,IP为192.168.0.105。执行ifconfig命令,找到ens33的inet就是IP地址

# ifconfig
……省略……
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.105
……省略……

测试1111端口

在浏览器里访问【http://192.168.0.105:1111/hello】,可以看到代理成功

代理到nginx_test_1

访问不存在的url进行404跳转测试,可以看到成功跳转到配置的百度页面了

nginx_test_1进行404测试

测试2222端口

在浏览器里输入url【http://192.168.0.105:2222/hello】进行访问,可以看到成功代理到9292端口所在的spring boot web应用了。

代理到nginx_test_2

访问不存在的url进行404测试,成功跳转到必应的搜索页面了

nginx_test_2进行404测试

完结

撒花完结,很简单的配置,学到了Nginx反向代理的基础操作,以后要多看看大佬的配置去学啊~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值