From 57c9dd4102486be4ad3f7685b0577271906df24b Mon Sep 17 00:00:00 2001
From: Fred Cox <mcfedr@gmail.com>
Date: Wed, 20 Sep 2023 20:51:34 +0100
Subject: [PATCH] reverseproxy: only change the content-length header when the
 full request was buffered

fixes: https://github.com/caddyserver/caddy/issues/5829

Signed-off-by: Fred Cox <mcfedr@gmail.com>
---
 modules/caddyhttp/reverseproxy/reverseproxy.go | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go
index 64a7d7ae057..42928a64f06 100644
--- a/modules/caddyhttp/reverseproxy/reverseproxy.go
+++ b/modules/caddyhttp/reverseproxy/reverseproxy.go
@@ -582,8 +582,12 @@ func (h Handler) prepareRequest(req *http.Request, repl *caddy.Replacer) (*http.
 	// feature if absolutely required, if read timeouts are
 	// set, and if body size is limited
 	if h.RequestBuffers != 0 && req.Body != nil {
-		req.Body, req.ContentLength = h.bufferedBody(req.Body, h.RequestBuffers)
-		req.Header.Set("Content-Length", strconv.FormatInt(req.ContentLength, 10))
+		var readBytes int64
+		req.Body, readBytes = h.bufferedBody(req.Body, h.RequestBuffers)
+		if h.RequestBuffers == -1 {
+			req.ContentLength = readBytes
+			req.Header.Set("Content-Length", strconv.FormatInt(req.ContentLength, 10))
+		}
 	}
 
 	if req.ContentLength == 0 {