Nginx 实战-05-nginx 反向代理实现域名到指定的 ip

前言

大家好,我是老马。很高兴遇到你。

我们为 java 开发者实现了 java 版本的 nginx

https://github.com/houbb/nginx4j

如果你想知道 servlet 如何处理的,可以参考我的另一个项目:

手写从零实现简易版 tomcat minicat

手写 nginx 系列

如果你对 nginx 原理感兴趣,可以阅读:

从零手写实现 nginx-01-为什么不能有 java 版本的 nginx?

从零手写实现 nginx-02-nginx 的核心能力

从零手写实现 nginx-03-nginx 基于 Netty 实现

从零手写实现 nginx-04-基于 netty http 出入参优化处理

从零手写实现 nginx-05-MIME类型(Multipurpose Internet Mail Extensions,多用途互联网邮件扩展类型)

从零手写实现 nginx-06-文件夹自动索引

从零手写实现 nginx-07-大文件下载

从零手写实现 nginx-08-范围查询

从零手写实现 nginx-09-文件压缩

从零手写实现 nginx-10-sendfile 零拷贝

从零手写实现 nginx-11-file+range 合并

从零手写实现 nginx-12-keep-alive 连接复用

从零手写实现 nginx-13-nginx.conf 配置文件介绍

从零手写实现 nginx-14-nginx.conf 和 hocon 格式有关系吗?

从零手写实现 nginx-15-nginx.conf 如何通过 java 解析处理?

从零手写实现 nginx-16-nginx 支持配置多个 server

目标

我想实现访问 http://github/houbb 转发到 http://127.0.0.1:3000

准备工作

实现一个简单的 http 服务

nodejs http

>node -v
v20.10.0

>npm -v
10.2.3

代码编写

const http = require('http');

// 创建一个 HTTP 服务器
const server = http.createServer((req, res) => {
  // 设置响应头
  res.writeHead(200, {'Content-Type': 'text/plain'});
  // 发送响应内容
  res.end('Hello World!\n');
});

// 监听端口 3000
server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000/');
});

启动

λ node http.js
Server running at http://127.0.0.1:3000/

测试效果:

>curl http://127.0.0.1:3000/
Hello World!

如何通过 nginx 设置反向代理,让我们访问 http://githubhoubb 的请求转发到 http://127.0.0.1:3000

要通过 Nginx 设置反向代理,将访问 http://githubhoubb 的请求转发到 http://127.0.0.1:3000,需要编辑 Nginx 的配置文件来定义一个 server 块和 location 块。

以下是配置的示例步骤:

1. 修改配置文件

找到 nginx 文件,

添加 server 块**:在 http 块内部,添加一个新的 server 块,用于监听 80 端口(HTTP 默认端口):

```nginx
server {
    listen 80;
    server_name githubhoubb;  # 这里应为 githubhoubb 或者你希望的域名

    location / {
        proxy_pass http://127.0.0.1:3000;  # 转发到本机的 3000 端口
        proxy_set_header Host $host;  # 设置原始请求的 Host 头
        proxy_set_header X-Real-IP $remote_addr;  # 设置原始请求的 IP 地址
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  # 设置 X-Forwarded-For 头
        proxy_set_header X-Forwarded-Proto $scheme;  # 设置 X-Forwarded-Proto 头
    }
}
```

2. 验证配置正确性:

λ nginx -t
nginx: the configuration file D:\tool\nginx\nginx-1.26.0\nginx-1.26.0/conf/nginx.conf syntax is ok
nginx: configuration file D:\tool\nginx\nginx-1.26.0\nginx-1.26.0/conf/nginx.conf test is successful

3. 重载 Nginx 配置

为了使更改生效,你需要重载 Nginx 的配置。在命令行中运行以下命令:

```sh
nginx -s reload
```

4. 测试验证

curl http://githubhoubb

现在,当你尝试访问 http://githubhoubb(或者你在 server_name 中设置的域名),请求应该会被转发到 http://127.0.0.1:3000

发现,依然无效。

λ curl http://githubhoubb
curl: (6) Could not resolve host: githubhoubb

发现这里如果想成功,必须和 DNS 结合起来。

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值