UPD: Springfox is abandoned

Springfox Swagger had always been kinda dirty solution with a lot of unclearness and bugs, but by now (2021 Q4) it hadn't been updated for more than a year.

The final straw was the fact that Springfox Swagger 3.0 doesn't work anymore with Spring Boot 2.6.x.

So, if you reading this, please, consider switching over to https://springdoc.org/ instead.

It's a pretty straightforward conversion and they do a great job of documenting it. https://springdoc.org/#migrating-from-springfox.

For those who use Springfox Swagger 3.0.0

Here's the working configuration for changing base url for docs:

springfox:
  documentation:
    swaggerUi:
      baseUrl: /documentation
    openApi:
      v3:
        path: /documentation/v3/api-docs
    swagger:
      v2:
        path: /documentation/v2/api-docs
Answer from RomanMitasov on Stack Overflow
Top answer
1 of 5
13

UPD: Springfox is abandoned

Springfox Swagger had always been kinda dirty solution with a lot of unclearness and bugs, but by now (2021 Q4) it hadn't been updated for more than a year.

The final straw was the fact that Springfox Swagger 3.0 doesn't work anymore with Spring Boot 2.6.x.

So, if you reading this, please, consider switching over to https://springdoc.org/ instead.

It's a pretty straightforward conversion and they do a great job of documenting it. https://springdoc.org/#migrating-from-springfox.

For those who use Springfox Swagger 3.0.0

Here's the working configuration for changing base url for docs:

springfox:
  documentation:
    swaggerUi:
      baseUrl: /documentation
    openApi:
      v3:
        path: /documentation/v3/api-docs
    swagger:
      v2:
        path: /documentation/v2/api-docs
2 of 5
4

You can edit your SwaggerConfiguration like that:

Take care to replace the package (which need to be the one containing your REST controllers), the host, and the PATH you need

@Configuration
@EnableSwagger2
public class SwaggerConfiguration implements WebMvcConfigurer {

    public static final String PATH = "/myapi";

    @Bean
    public Docket api() {
        final var package = "com.julia.rest";
        final var host = "localhost:8080";

        return new Docket(DocumentationType.SWAGGER_2)
                .host(host)
                .select()
                .apis(RequestHandlerSelectors.basePackage(package))
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        final var apiDocs = "/v2/api-docs";
        final var configUi = "/swagger-resources/configuration/ui";
        final var configSecurity = "/swagger-resources/configuration/security";
        final var resources = "/swagger-resources";

        registry.addRedirectViewController(PATH + apiDocs, apiDocs).setKeepQueryParams(true);
        registry.addRedirectViewController(PATH + resources, resources);
        registry.addRedirectViewController(PATH + configUi, configUi);
        registry.addRedirectViewController(PATH + configSecurity, configSecurity);
        registry.addRedirectViewController(PATH, "/");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(PATH + "/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}

Another solution is by changing the spring-boot URL context-path:

Edit pour application.properties file:

server.servlet.context-path=/myapi

Or if you have an application.yml file:

server:
  servlet:
    context-path: /myapi

Warning: It will change the base path of all your web services, not only Swagger

🌐
Baeldung
baeldung.com › home › spring › spring boot › change swagger-ui url prefix
Change Swagger-UI URL prefix - Spring Boot
May 11, 2024 - Learn how to change the Swagger-UI URL prefix when using Springfox and how to set up the REST API documentation using OpenAPI 3.0 with redirections.
🌐
GitHub
github.com › springfox › springfox › issues › 2432
how to change base path for swagger 2.8 with spring boot 2.0 · Issue #2432 · springfox/springfox
May 21, 2018 - @Bean public Docket productApi(ServletContext servletContext) { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("com.test.swagger")) .build().apiInfo(metaData()); } private ApiInfo metaData() { return new ApiInfoBuilder().title("Spring Boot REST API") .description("\"Spring Boot REST API for Test\"").version("1.0.0") .license("Apache License Version 2.0").licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"") .contact( new Contact("Test", "http://test.com/", "test@gmail.com")) .build(); }
Published   May 21, 2018
Author   naren19
🌐
GitHub
github.com › springfox › springfox › issues › 1443
how to change base path for swagger 2.0 · Issue #1443 · springfox/springfox
August 10, 2016 - { "swagger": "2.0", "info": { "description": "This API is for test", "version": "SNAPSHOT", "license": { "name": "License", "url": "/public/footer.html" } }, "host": "localhost:8080", "basePath": "/myapi", My project is Spring boot, current the swagger configuration is: @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()) .globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder() .code(
Author   jiangchuan1220
🌐
CopyProgramming
copyprogramming.com › howto › change-swagger-ui-base-path-in-spring-boot
Swagger Change Base URL in Spring Boot: Complete Guide 2026
December 6, 2025 - The latest version (2.8.14) provides ... Swagger UI documentation. Configuring Swagger base URLs in Spring Boot is straightforward with the latest springdoc-openapi library....
🌐
GitHub
github.com › apigee-127 › swagger-tools › issues › 567
how to do friendly base url for swagger 2.8.0 · Issue #567 · apigee-127/swagger-tools
April 10, 2018 - I'm trying to change base url for API documentation. The base url is "http://localhost:8080/swagger-ui.html". I want to get something like "http://localhost:8080/myapi/swagger-ui.html". I use Springfox 2.8.0 Swagger, Java 8, Spring Boot 2.0 The swagger configuration is: @Configuration @EnableSwagger2 public class SwaggerConfiguration { @Bean public Docket api(ServletContext servletContext) { return new Docket(DocumentationType.SWAGGER_2) .pathProvider(new RelativePathProvider(servletContext) { @Override public String getApplicationBasePath() { return "/myapi"; } }) .select() .apis(RequestHandlerSelectors.any()) .paths(Predicates.not(PathSelectors.regex("/error"))) .build() .useDefaultResponseMessages(false); } } Custom path provider had to help, but I still get access to api documentation by using url "http://localhost:8080/swagger-ui.html".
Author   julyaTyrer
🌐
Apidog
apidog.com › blog › swagger-ui-url
How to Change Swagger UI URL Defauth Path
February 5, 2026 - To find the URL, follow these steps: Ensure your project is configured to generate Swagger documentation. To access the Swagger UI, you need to combine the base URL of your API with the Swagger documentation endpoint.
🌐
GitHub
github.com › springfox › springfox › issues › 963
Customising the displayed base URL for API endpoints · Issue #963 · springfox/springfox
GET /record/{collectionId}/{recordId}/ancestor-self-siblings.json GET /record/{collectionId}/{recordId}/children.json GET /record/{collectionId}/{recordId}/parent.json GET /record/{collectionId}/{recordId}/self.json (...) [ base url: /api/v2 , api version: 1.0 ]...
🌐
Swagger
swagger.io › docs › specification › v3_0 › api-host-and-base-path
API Server and Base Path | Swagger Docs
In OpenAPI 3.0, you use the servers array to specify one or more base URLs for your API. servers replaces the host, basePath and schemes keywords used in OpenAPI 2.0.
Find elsewhere
🌐
Swagger
swagger.io › docs › specification › v2_0 › api-host-and-base-path
API Host and Base Path | Swagger Docs
November 12, 2018 - All API paths are relative to this base URL, for example, /users actually means <scheme>://<host>/<basePath>/users.
🌐
Medium
medium.com › தழலி › documenting-spring-boot-api-using-swagger2-14926e8e20a4
Documenting Spring Boot API using Swagger2 | by Sivaram Rasathurai | Javarevisited | Medium
December 9, 2024 - We want to update the documentation whenever the code gets changed. SpringFox will do this for us. It can automatically inspect our classes, detect Controllers, their methods, model classes they use, and URLs to which they are mapped. Did you have a REST API? Then you can document your REST API using swagger2 with the following sections. If you don’t have a REST API, don’t worry, clone my Git repository and check out the “start-point” branch. You will have an undocumented Spring boot ...
🌐
Stack Overflow
stackoverflow.com › questions › 49766074 › change-swagger-ui-base-path-in-spring-boot
Change swagger ui base path in spring boot - Stack Overflow
@Bean public Server rsServer() { JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean(); endpoint.setBus(bus); endpoint.setAddress("/gbservice"); endpoint.setServiceBeans(Arrays.<Object>asList(new HelloResourceImpl())); endpoint.setFeatures(Arrays.asList(swagger2Feature())); endpoint.setProvider(jsonProvider()); return endpoint.create(); } @Bean("swagger2Feature") public Feature swagger2Feature() { Swagger2Feature result = new Swagger2Feature(); result.setTitle("Spring Boot + CXF + Swagger Example"); result.setDescription("Spring Boot + CXF + Swagger Example description"); result.setBa
🌐
SNOMED Confluence
confluence.ihtsdotools.org › display › MT › Configuring+Swagger
Configuring Swagger - SNOMED International Mapping Tool - SNOMED Confluence
December 1, 2014 - <!-- Swagger configuration --> <servlet> <servlet-name>JerseyJaxrsConfig</servlet-name> <servlet-class>com.wordnik.swagger.jersey.config.JerseyJaxrsConfig</servlet-class> <init-param> <param-name>api.version</param-name> <param-value>1.0.0</param-value> </init-param> <init-param> <!-- This URL is the path to the REST web service itself. In the index.html page is the path to the api-docs page --> <param-name>swagger.api.basepath</param-name> <param-value>${base.url}</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet>
🌐
Medium
apu-pradhan.medium.com › how-to-set-up-swagger-in-spring-boot-68b3fe862a0d
How to Set Up Swagger in Spring Boot | by Apu | Medium
November 18, 2024 - Use the correct URL: /swagger-ui/index.html for newer versions. Ensure your controllers are located in packages scanned by Spring Boot.
Top answer
1 of 3
10

UPD: Springfox is abandoned

Springfox Swagger had always been kinda dirty solution with a lot of unclearness and bugs, but by now (2021 Q4) it hadn't been updated for more than a year.

The final straw was the fact that Springfox Swagger 3.0 doesn't work anymore with Spring Boot 2.6.x.

So, if you reading this, please, consider switching over to https://springdoc.org/ instead.

It's a pretty straightforward conversion and they do a great job of documenting it. https://springdoc.org/#migrating-from-springfox.

Original answer

I've found a working solution for Springfox 3.0.0 here:

springfox:
  documentation:
    swaggerUi:
      baseUrl: /documentation
    openApi:
      v3:
        path: /documentation/v3/api-docs
    swagger:
      v2:
        path: /documentation/v2/api-docs

Configuration above will change base-path for Swagger endpoints to /documentation without any redirects and other crutches.

It is sad that these configurations is missing in the docs tho.

2 of 3
6

Try this configuration class.

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

  @Bean
  public Docket productApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select().apis(RequestHandlerSelectors.basePackage(""my.favorite.package""))
                        .paths(regex(PathSelectors.any()))
        .build();

  }

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs").setKeepQueryParams(true);
    registry.addRedirectViewController("/documentation/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
    registry.addRedirectViewController("/documentation/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
    registry.addRedirectViewController("/documentation/swagger-resources", "/swagger-resources");
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/documentation/**").addResourceLocations("classpath:/META-INF/resources/");
  }


}
🌐
Stack Overflow
stackoverflow.com › questions › 58803830 › swagger-configuration-for-base-url
spring boot - Swagger Configuration for base url - Stack Overflow
Looks like setting the URL environment variable for the swagger UI should work. For better control, you can get a copy of the dist/index.html page, edit it with your configuration options, and mount it into the swagger container. ... Sign up to request clarification or add additional context in comments. ... My answer is straight forward WRT Kubernetes + SpringBoot.
🌐
GitHub
github.com › springfox › springfox › issues › 1996
Swagger ui stuck on unable to infer base url · Issue #1996 · springfox/springfox
August 23, 2017 - return new Docket(DocumentationType.SWAGGER_2) .host("http://localhost:8999") .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); I have tried different possibilities of host configuration, including not providing it at all. I can access the docs json from http://localhost:8999/v2/api-docs just fine. When I try to set the base url through this message, no matter what I enter, the dialog flickers and just stands there.
Author   muudyguy
🌐
Stack Overflow
stackoverflow.com › questions › 76574123 › unable-to-infer-base-url-error-with-swagger-ui › 76579558
spring boot - Unable to infer base url, error with Swagger UI - Stack Overflow
For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually: ... Add .pathMapping("/") after build() in swagger config. ... Sign up to request clarification or add additional context in comments. ... check these springfox-demos and see what configuration suits your build.
Top answer
1 of 3
3

I had a similar task for Spring Boot 2.5.6 and springdoc-openapi-webflux-ui 1.5.12. I've found several possible solutions for myself. Maybe it will be helpful for somebody else.


Set springdoc.swagger-ui.path directly

The straightforward way is to set property springdoc.swagger-ui.path=/custom/path. It will work perfectly if you can hardcode swagger path in your application.


Override springdoc.swagger-ui.path property

You can change default swagger-ui path programmatically using ApplicationListener<ApplicationPreparedEvent>. The idea is simple - override springdoc.swagger-ui.path=/custom/path before your Spring Boot application starts.

@Component
public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> {

    @Override
    public void onApplicationEvent(final ApplicationPreparedEvent event) {
        ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
        Properties props = new Properties();
        props.put("springdoc.swagger-ui.path", swaggerPath());
        environment.getPropertySources()
                .addFirst(new PropertiesPropertySource("programmatically", props));
    }

    private String swaggerPath() {
        return "/swagger/path"; //todo: implement your logic here.
    }
}

In this case, you must register the listener before your application start:

@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "APIs", version = "0.0.1", description = "APIs v0.0.1"))
public class App {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(App.class);
        application.addListeners(new SwaggerConfiguration());
        application.run(args);
    }
}

Redirect using controller


You can also register your own controller and make a simple redirect (the same as what you suggest, but in my case, I need to use the WebFlux approach):

@RestController
public class SwaggerEndpoint {

    @GetMapping("/custom/path")
    public Mono<Void> api(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.PERMANENT_REDIRECT);
        response.getHeaders().setLocation(URI.create("/swagger-ui.html"));
        return response.setComplete();
    }
}

The problem with such an approach - your server will still respond if you call it by address "/swagger-ui.html".

2 of 3
2

Apparantly the library integrates natively only with spring-boot applications like you mentioned in your comment. If you want to use spring, it's possible but the integration details aren't documented, because it really depends on the version/module and the nature of you spring application.

You can check the FAQ to see if it answers your questions.

There are some more answers here on SO.