Duplicate Response Headers in Nginx Despite Using proxy_pass and rewrite break

Description:

I am facing an issue in Nginx where certain response headers, such as Strict-Transport-Security, and X-Request-Time, are appearing twice in the response headers.

Issue Details:

  • I have multiple location blocks handling API routes (/api/1.1/…).
  • I use proxy_pass to forward requests to an upstream server (api2).
  • I have used rewrite … break; inside some location blocks, expecting that once a request matches, it should not be evaluated further.
  • Despite this, some requests appear to be processed by multiple location blocks, causing duplicate headers in the response.

Debugging Steps Taken:

  1. Checked Logs: Used log_format and added custom response headers to confirm that some requests are processed more than once.
  2. Enabled Debug Mode: error_log /var/log/nginx/error.log debug; rewrite_log on; revealed that certain requests might be internally redirected.

Questions:

  1. Why is Nginx evaluating multiple location blocks for the same request even after using rewrite … break;?
  2. How can I ensure that a request is handled by only one location block and does not proceed to another?
  3. Is there a way to completely prevent duplicate headers in the response when using proxy_pass?

Moving to Troubleshooting category.