如何解决如何在nginx中为多个网站创建反向代理
我有许多不同的技术在我的本地机器上提供 API 和站点。我希望能够通过人类可读的名称而不是端口来查看它们。
例如,我有:
- localhost:8000 => 用于用户面板的 laravel api
- localhost:8001 => 管理面板的 laravel api
- localhost:3000 => 为用户面板响应客户端
- localhost:3001 => 站点的 nextjs 客户端
- localhost:3002 => 为管理面板响应客户端
这个列表还在继续。
当然不可能记住所有这些端口。因此我想为他们设置一个反向代理:
- api.user.example.local
- api.admin.example.local
- example.local
- user.example.local
- admin.example.local
我知道我必须将这些主机头添加到 /etc/hosts
文件中。我还了解了 how to configure nginx as a reverse proxy for one domain。
我不知道如何为许多网站做到这一点。并且仅作为反向代理,而不是作为服务器。
解决方法
请注意:我不认为自己是真正的超级 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;
}
}
在客户端机器上,将这些记录添加到 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
其中 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
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
有关 NGINX 反向代理的更多信息
NGINX Reverse Proxy
Module ngx_http_proxy_module
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。