Enabling Underscore Headers in Nginx for Spring Boot Applications
This article demonstrates how Nginx’s default behavior ignores request headers containing underscores, causing missing parameters in a Spring Boot application, and shows how to configure the 'underscores_in_headers on;' directive to correctly forward such headers, with code examples and testing via Postman.
Nginx is a high‑performance HTTP and reverse‑proxy server that has become a standard component in modern Java web applications, often used to improve throughput and availability.
However, Nginx has a default configuration that can be surprising: it silently drops request headers that contain underscores, which may cause unexpected bugs for developers unfamiliar with this behavior.
The article starts with a simple Spring Boot controller that returns a "Hello World" string:
package com.fullstack.commerce.user.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/hello")
public class HelloWorldController {
@GetMapping("world")
public String sayHello(HttpServletRequest request) {
return "Hello World!";
}
}Using Postman, the endpoint is verified to return the expected string when accessed directly on port 8081.
Next, a custom request header cur_location is added in Postman and the backend is debugged; the header value is correctly received, confirming the setup works without Nginx.
When Nginx is introduced as a reverse proxy, the following minimal configuration is used:
location / {
proxy_pass http://localhost:8081/;
}After restarting Nginx, the same Postman request is sent through port 80. Although the request reaches the backend, the cur_location header is now missing.
The cause is Nginx’s default rule that ignores headers containing underscores. To enable such headers, the directive underscores_in_headers on; must be added to nginx.conf and Nginx restarted:
underscores_in_headers on;After applying this change, the backend receives the cur_location header correctly, and the issue is resolved.
The article concludes by inviting readers to share their own experiences with similar Nginx header handling problems.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.