请注意:我并不认为自己是真正的超级 nginx 专家,只是开始学习 nginx,但我认为我可以帮助您完成这项任务。
这是我的方法:
首先,确保您的默认 nginx 配置(通常为 /etc/nginx/nginx.conf)在其 http 块中有行 include /etc/nginx/conf.d/*.conf;,因此您可以在单独的配置文件中指定内部服务器以方便使用。
创建额外的配置文件/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