村长大人 发表于 2025-3-13 17:42:22

【已解答】nginx反向代理错误

需求,有2个docker容器,一个在3000端口,一个在8080端口,有一个域名,想要使用域名访问3000端口,想要使用某个路径访问8080端口
使用路径匹配和路径重写,第二个路径一直报错404
location /web/ {
      proxy_pass http://localhost:3000/;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_redirect http://localhost:3000/ /web/;
    }

    location /admin/ {
      proxy_pass http://localhost:8080/;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_redirect http://localhost:8080/ /admin/;
    }
location ^~ / {
      proxy_pass http://127.0.0.1:3000;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
      proxy_http_version 1.1;

      add_header X-Cache $upstream_cache_status;

      # Set Nginx Cache
      set $static_file 0;
      if ($uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$") {
            set $static_file 1;
            expires 1m;
      }
      if ($static_file = 0) {
            add_header Cache-Control no-cache;
      }
    }

    location ^~ /admin {
      proxy_pass http://127.0.0.1:8080;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
      proxy_http_version 1.1;

      add_header X-Cache $upstream_cache_status;

      # Set Nginx Cache
      set $static_file 0;
      if ($uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$") {
            set $static_file 1;
            expires 1m;
      }
      if ($static_file = 0) {
            add_header Cache-Control no-cache;
      }
    }
    location / {
      proxy_pass http://localhost:3000;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 对于/service2/
    location /admin/ {
      rewrite ^/admin/(.*)$ /$1 break; # 去掉/service2/前缀
      proxy_pass http://localhost:8080;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
}





阿珂 发表于 2025-3-14 10:49:48

这个配置看起来冲突了,有两个/admin的配置,移除冲突的部分
页: [1]
查看完整版本: 【已解答】nginx反向代理错误