nginx - 用于弹簧启动应用程序的多个反向代理(启用弹簧安全性)



我有三个 Spring 引导应用程序在端口 8080、8081、8082 上的嵌入式 tomcat 上运行。

我正在尝试为所有这些配置反向代理,当点击 url 时,我收到来自 Spring 安全性的 401 错误。

我已经配置了nginx如下:

worker_processes  1;
events {
worker_connections  1024;
}

http {
include       mime.types;
default_type  application/octet-stream;
sendfile        on;
keepalive_timeout  65;
server {
listen       80;
server_name  localhost;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #also tried $remote_addr;
location /first {
proxy_pass http://localhost:8081;
}
location /second {
proxy_pass http://localhost:8080;
}
location = /third {
proxy_pass http://localhost:8082;
}
}
}

我尝试访问的网址是 http://localhost/second/这给了我错误说There was an unexpected error (type=Unauthorized, status=401). Full authentication is required to access this resource

尝试访问时 http://localhost:8080/swagger-ui.html 给我404错误。

当尝试访问时 http://localhost:8080/swagger-ui.html 向我显示预期的 Swagger 页面。

如果您仍在寻找答案,这就是我设法让它工作的方式:

  1. 除了让每个 spring-boot-app 在不同的端口上运行之外,还要确保每个 spring-boot-app 都有一个唯一的上下文路径。 查看一些 例子!关于如何 如果您不熟悉,可以实现这一目标。
  2. 只需将 spring-boot-app 的上下文路径与 nginx,像这样:

    location /first {
    proxy_pass http://localhost:8081/first;
    }
    location /second {
    proxy_pass http://localhost:8080/second;
    }
    location /third {
    proxy_pass http://localhost:8082/third;
    }
    

    我没有测试您的nginx配置,但是如果一切都配置正确,则上述步骤可能是您正在寻找的。

问题是nginx在浏览器上缓存页面,因此nginx.conf文件中的任何修改都不会反映在浏览器上。这是我的nginx.conf的最终工作版本

worker_processes  1;
events {
worker_connections  1024;
}

http {
include       mime.types;
default_type  application/octet-stream;
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
sendfile        on;
keepalive_timeout  65;
gzip  on;
server {
listen       80;
listen       [::]:80;
server_name  localhost;
access_log  logs/host.access.log  main;

location / {
root  "D:/projects/mySimpleProject/build";
index index.html index.htm;
}
location /first/ {
proxy_pass http://localhost:8080/;
}
location /second/ {
proxy_pass http://localhost:8081/;
}
location /third/ {
proxy_pass http://localhost:8082/;
}

error_page  404              /404.html;
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}
}
}

对于那些不知道的人,重新启动Nginx服务器并按ctrl + F5以刷新浏览器,每次在nginx.conf中进行更改时

最新更新