Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

How to Apply a Global URL Prefix to All Spring Boot Controllers

How to Apply a Global URL Prefix to All Spring Boot Controllers

This article explains multiple ways to apply a common URL prefix to all Spring Boot controllers, covering servlet‑context configuration, property settings, annotation‑based approaches, server‑side forwarding, and Nginx reverse‑proxy techniques, with code samples and discussion of their advantages and drawbacks.

1. Introduction

In Spring Boot each controller can have its own URL mapping, but sometimes a unified prefix is desired. This article explores several methods to set a common prefix for all controllers.

2. Based on Servlet Context

2.1 Configure DispatcherServlet Bean

@Configuration
public class DispatcherServletCustomConfiguration {
    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Bean
    public ServletRegistrationBean dispatcherServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
            dispatcherServlet(), "/api/");
        registration.setName("dispatcherServlet");
        return registration;
    }
}

This registers a DispatcherServlet with the URL prefix /api/, so all endpoints must be accessed through that base path.

2.2 Using Configuration Properties

Spring Boot 2.x and later allow setting the context path in application.yml:

server:
  servlet:
    contextPath: /api

For earlier versions the same effect can be achieved with:

server:
  contextPath: /api

Or with Spring MVC properties:

spring:
  mvc:
    servlet:
      path: /api

These approaches affect every endpoint in the application.

3. Annotation‑Based Methods

3.1 Using SpEL with @RequestMapping

@Controller
@RequestMapping(path = "${pack.app.apiPrefix}/users")
public class UserController {
}

The prefix is defined in the configuration property pack.app.apiPrefix.

3.2 Custom Annotation

@RequestMapping(value = "/api/")
public @interface PackMapping {
}

// Usage
@RestController
@PackMapping
public class SomeController {
    @RequestMapping("/users")
    public String getAll() {
        return "...";
    }
}

Custom annotations allow fine‑grained control, applying the prefix only to selected controllers.

4. Server‑Side Forwarding

@RestController
public class EndpointController {
    @GetMapping("/endpoint1")
    public String endpoint1() { return "Hello from endpoint 1"; }

    @GetMapping("/endpoint2")
    public String endpoint2() { return "Hello from endpoint 2"; }
}

A routing controller forwards requests based on a custom header:

@Controller
@RequestMapping("/api/endpoint")
public class ApiPrefixController {
    @GetMapping
    public ModelAndView route(ModelMap model, HttpServletRequest request) {
        String action = request.getHeader("X-ACTION");
        return switch (action) {
            case null -> new ModelAndView("forward:/error");
            case "xxx" -> new ModelAndView("forward:/endpoint1", model);
            case "zzz" -> new ModelAndView("forward:/endpoint2", model);
            default -> new ModelAndView("forward:/home");
        };
    }
}

5. Nginx Reverse Proxy

server {
    listen 80;
    server_name default;

    location /api/ {
        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-NginX-Proxy true;

        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://www.pack.com;
    }
}

This method adds the prefix at the web server level without modifying application code.

Pros and Cons

Servlet‑context and property approaches affect every endpoint, which may be unsuitable for services that need unprefixed paths (e.g., OAuth callbacks). Annotation‑based solutions provide granular control, allowing only selected controllers to use the prefix.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
backendnginxannotationspring-bootdispatcher-servleturl-prefix

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion