如何在nginx中为多个网站创建反向代理

Hos*_*lah 6 reverse-proxy nginx

我有许多不同的技术在我的本地计算机上为 API 和站点提供服务。我希望能够通过人类可读的名称而不是端口来查看它们。

例如,我有:

  • localhost:8000 => 用户面板的 laravel api
  • localhost:8001 => 用于管理面板的 laravel api
  • localhost:3000 => 对用户面板做出反应客户端
  • localhost:3001 => 站点的 nextjs 客户端
  • 本地主机:3002 => 为管理面板反应客户端

这个清单还在继续。

当然,记住所有这些端口是不可能的。因此我想为他们设置一个反向代理:

  • api.user.example.local
  • api.admin.example.local
  • 示例.local
  • 用户.example.local
  • 管理员.example.local

我知道我必须将这些主机头添加到/etc/hosts文件中。我还阅读了如何将 nginx 配置为一个域的反向代理

我不知道如何为许多网站做到这一点。并且仅作为反向代理,不作为服务器。

Dmi*_*try 18

请注意:我并不认为自己是真正的超级 nginx 专家,刚刚开始学习 nginx,但我认为我可以帮助您完成这项任务。

这是我的方法:

首先,确保您的默认 nginx 配置(通常)在其块中/etc/nginx/nginx.conf有一行,因此您可以在单独的配置文件中指定内部服务器以方便使用。include /etc/nginx/conf.d/*.conf;http

创建额外的配置文件/etc/nginx/conf.d/local_domains.conf并在其中添加以下服务器块:

server {
    listen         80;
    server_name    api.user.example.local;

    location / {
    set $target http://localhost:8000;
    proxy_pass $target;
  }
}

server {
    listen         80;
    server_name    api.admin.example.local;

    location / {
    set $target http://localhost:8001;
    proxy_pass $target;
  }
}

server {
    listen         80;
    server_name    example.local;

    location / {
    set $target http://localhost:3000;
    proxy_pass $target;
  }
}

server {
    listen         80;
    server_name    user.example.local;

    location / {
    set $target http://localhost:3001;
    proxy_pass $target;
  }
}

server {
    listen         80;
    server_name    admin.example.local;

    location / {
    set $target http://localhost:3002;
    proxy_pass $target;
  }
}
Run Code Online (Sandbox Code Playgroud)

在客户端计算机上,将这些记录添加到文件hosts

192.168.1.1  api.user.example.local
192.168.1.1  api.admin.example.local
192.168.1.1  example.local
192.168.1.1  user.example.local
192.168.1.1  admin.example.local
Run Code Online (Sandbox Code Playgroud)

192.168.1.1你的 nginx 服务器的地址在哪里。

就是这样,如果您的内部服务器使用 HTTP 协议,它应该可以工作。

但如果您需要对内部服务器和主 nginx 服务器使用 HTTPS,请按如下方式修改每个服务器块:

server {
    listen         443 ssl http2;
    server_name    api.user.example.local;

    ssl_certificate          /usr/local/share/ca-certificates/example.local.crt;
    ssl_certificate_key      /usr/local/share/ca-certificates/example.local.key;
    add_header Strict-Transport-Security "max-age=31536000" always;

    location / {
    set $target https://api.user.example.local:8000;
    proxy_pass $target;
  }
}

and so on
Run Code Online (Sandbox Code Playgroud)

ssl_certificate并且ssl_certificate_key应该指向域的正确证书和密钥文件。

如果您希望 nginx 主服务器侦听端口 80 并将所有流量重定向到 https,请为每个服务器添加额外的服务器块:

server {
    server_name api.user.example.local;
    listen 80;

  # Force redirection to https on nginx side
  location / {
        return 301 https://$host$request_uri;
    }
}

and so on
Run Code Online (Sandbox Code Playgroud)

有关 NGINX 反向代理的更多信息
NGINX 反向代理
模块 ngx_http_proxy_module