From 0130b699df7a3e669a60732b465079cdd7a4addb Mon Sep 17 00:00:00 2001
From: Matthew Holt <mholt@users.noreply.github.com>
Date: Thu, 27 Feb 2020 20:52:41 -0700
Subject: [PATCH] cmd/reverse_proxy: Add --change-host-header flag

"Transparent mode" is the default, just like the actual handler.
---
 modules/caddyhttp/reverseproxy/command.go | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)

diff --git a/modules/caddyhttp/reverseproxy/command.go b/modules/caddyhttp/reverseproxy/command.go
index 1638d823b..c47447fb5 100644
--- a/modules/caddyhttp/reverseproxy/command.go
+++ b/modules/caddyhttp/reverseproxy/command.go
@@ -36,7 +36,7 @@ func init() {
 	caddycmd.RegisterCommand(caddycmd.Command{
 		Name:  "reverse-proxy",
 		Func:  cmdReverseProxy,
-		Usage: "[--from <addr>] [--to <addr>]",
+		Usage: "[--from <addr>] [--to <addr>] [--change-host-header]",
 		Short: "A quick and production-ready reverse proxy",
 		Long: `
 A simple but production-ready reverse proxy. Useful for quick deployments,
@@ -46,11 +46,16 @@ Simply shuttles HTTP traffic from the --from address to the --to address.
 
 If the --from address has a domain name, Caddy will attempt to serve the
 proxy over HTTPS with a certificate.
+
+If --change-host-header is set, the Host header on the request will be modified
+from its original incoming value to the address of the upstream. (Otherwise, by
+default, all incoming headers are passed through unmodified.)
 `,
 		Flags: func() *flag.FlagSet {
 			fs := flag.NewFlagSet("file-server", flag.ExitOnError)
-			fs.String("from", "", "Address to receive traffic on")
-			fs.String("to", "", "Upstream address to proxy traffic to")
+			fs.String("from", "", "Address on which to receive traffic")
+			fs.String("to", "", "Upstream address to which to to proxy traffic")
+			fs.Bool("change-host-header", false, "Set upstream Host header to address of upstream")
 			return fs
 		}(),
 	})
@@ -59,6 +64,7 @@ proxy over HTTPS with a certificate.
 func cmdReverseProxy(fs caddycmd.Flags) (int, error) {
 	from := fs.String("from")
 	to := fs.String("to")
+	changeHost := fs.Bool("change-host-header")
 
 	if from == "" {
 		from = "localhost:" + httpcaddyfile.DefaultPort
@@ -97,13 +103,16 @@ func cmdReverseProxy(fs caddycmd.Flags) (int, error) {
 	handler := Handler{
 		TransportRaw: caddyconfig.JSONModuleObject(ht, "protocol", "http", nil),
 		Upstreams:    UpstreamPool{{Dial: toURL.Host}},
-		Headers: &headers.Handler{
+	}
+
+	if changeHost {
+		handler.Headers = &headers.Handler{
 			Request: &headers.HeaderOps{
 				Set: http.Header{
-					"Host": []string{"{http.reverse_proxy.upstream.host}"},
+					"Host": []string{"{http.reverse_proxy.upstream.hostport}"},
 				},
 			},
-		},
+		}
 	}
 
 	route := caddyhttp.Route{