Nginx 实战二(反向代理)

1,436 阅读2分钟

创建测试域名

首先我们在本地创建一个自定义测试域名dacongming.com,修改本地 hosts 文件完成域名绑定
执行 vim /private/etc/hosts 在 hosts 文件添加一行,保存退出(如果没有权限可以先执行 sudo su) 就是告诉我们的电脑访问 dacongming.com 的时候, 无需请求 DNS, 直接指向我们本机

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
127.0.0.1       0.0.0.0
# 添加 dacongming.com
127.0.0.1       dacongming.com
255.255.255.255 broadcasthost
::1             localhost

# Added by Docker Desktop
# To allow the same kube context to work on the host and the container:

# End of section

我们 ping 一下这个域名 dacongming.com,查看是否绑定成功

image.png 出现此结果表明绑定成功

修改 nginx 配置

命令行切换到 nginx 配置目录下 cd /usr/local/etc/nginxvim nginx.conf

image.png 修改 server 模块,将请求转发到 B 站,保存退出,启动 nginx(sudo nginx)

server {
    # 监听80端口号
    listen 80;

    # 监听访问的域名
    server_name dacongming.com;

     # 根据访问路径配置
    location / {
        # 把请求转发到
        proxy_pass https://bilibili.com;
    }
}

我们尝试访问下 dacongming.com

image.png 可以看到我们已经成功把请求转发到了 B 站(由于 B 站资源做了域名访问限制,所以图片加载不出来)

创建跨域请求

我们在本地新建两个文件,分别是模拟客户端与服务端 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h3>nginx 反向代理</h3>

  <script>
      var xhr = new XMLHttpRequest()
      xhr.open('GET', 'http://localhost:9000')
      xhr.onreadystatechange = function() {
          if(xhr.readyState === 4 && xhr.status === 200) {
              console.log(xhr.responseText)
          }
      }
      xhr.send()
  </script>
</body>
</html>

server.js

const http = require('http');
const server = http.createServer();
const host = '0.0.0.0'
const port = 9000
let n = 0
server.on('request'function (req, res) {
  n += 1
  console.log('请求来了: ', n)
  res.write('Hello World!!!');
  res.end();
});
server.listen(port, host, function () {
  console.log(`服务器启动了,请访问:http://${host}:${port}`);
})

分别启动 index.htmlserver.js 我们打开浏览器可以看到由于端口号不同,出现了跨域问题

image.png

配置 nginx 代理

  1. dacongming.com 转发到 http://localhost:52330,重启 nginx
server {
    # 监听80端口号
    listen 80;

    # 监听访问的域名
    server_name dacongming.com;

    # 根据访问路径配置
    location / {
        # 把 dacongming.com 请求转发到 index.html
        proxy_pass http://localhost:52330;
    }
}

image.png 2. 修改 index.html 请求

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h3>nginx 反向代理</h3>

  <script>
      var xhr = new XMLHttpRequest()
      // 将 http://localhost:9000 改为 /api
      xhr.open('GET', '/api/getName')
      xhr.onreadystatechange = function() {
          if(xhr.readyState === 4 && xhr.status === 200) {
              console.log(xhr.responseText)
          }
      }
      xhr.send()
  </script>
</body>
</html>

3.修改 nginx 配置,监听 /api 请求,转发到 http://0.0.0.0:9000,重启nginx

server {
    # 监听80端口号
    listen 80;

    # 监听访问的域名
    server_name dacongming.com;

    # 根据访问路径配置
    location / {
        # 把 dacongming.com 请求转发到 index.html
        proxy_pass http://localhost:52330;
    }
    location /api/ {
        # 监听 /api 请求转发到 server.js
        proxy_pass http://0.0.0.0:9000;
    }
}

我们刷新下 dacongming.com 看看

image.png 可以看到报错已经消失,结果已经正常返回了