You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx代理下swagger-ui请求路径异常的解决方法

解决SpringDoc Swagger UI在Nginx反向代理下的前缀缺失问题

问题核心

当前配置下,Swagger UI未正确识别Nginx反向代理的/api前缀,导致直接请求/v3/api-docs而非正确的/api/v3/api-docs。

可行解决方案

方案一:直接配置SpringDoc属性(推荐)

在application.properties中添加以下配置,强制指定Swagger UI请求的API文档地址:

# 指定后端内部API文档路径
springdoc.api-docs.path=/v3/api-docs
# 指定Swagger UI的访问路径
springdoc.swagger-ui.path=/swagger-ui/index.html
# 关键配置:指定Swagger UI要请求的API文档完整路径(相对于前端访问根路径)
springdoc.swagger-ui.url=/api/v3/api-docs

配置后,Swagger UI会直接向/api/v3/api-docs发起请求,与Nginx的代理规则匹配。

方案二:自定义SpringDoc配置类

如果需要更灵活的控制,可以创建配置类显式设置Swagger UI的请求地址:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springdoc.core.configuration.SpringDocUIConfigProperties;
import org.springdoc.core.models.GroupedOpenApi;

@Configuration
public class SwaggerConfiguration {

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group("public-api")
                .pathsToMatch("/**")
                .build();
    }

    @Bean
    public SpringDocUIConfigProperties swaggerUiConfig() {
        SpringDocUIConfigProperties config = new SpringDocUIConfigProperties();
        // 设置Swagger UI请求的API文档地址
        config.setUrl("/api/v3/api-docs");
        return config;
    }
}

方案三:调整Nginx配置(补充资源路径适配)

如果希望通过Nginx层面解决,可以修改现有location规则,确保Swagger UI静态资源加载时传递正确前缀:

location ~ ^/api(/|$) {
    rewrite ^/api(/|$)(.*)$ /$2 break;
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-proto https;
    proxy_set_header X-Forwarded-Prefix "/api";
}

# 额外适配Swagger UI静态资源路径
location ~ ^/swagger-ui(/|$) {
    rewrite ^/swagger-ui(/|$)(.*)$ /swagger-ui/$2 break;
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Prefix "/api";
}

此方式需维护额外Nginx规则,优先级低于前两种方案。

说明

尽管已配置X-Forwarded-Prefix和Spring转发头策略,但SpringDoc在部分版本中无法自动基于该前缀生成Swagger UI请求路径,因此显式指定springdoc.swagger-ui.url是最直接有效的解决方式。

内容的提问来源于stack exchange,提问作者morpheus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:11:07