(Caddy 0.10.11+) + snippet + redir

Hello,

I have tried to create some snippets to handle redirect on many situations, below:

(any443-any80) {
	redir 308 {
		if {>X-Forwarded-Proto} is https
		/ http://{host}{uri}
	}
}

(any80-any443) {
	redir 308 {
		if {>X-Forwarded-Proto} is http
		/ https://{host}{uri}
	}
}

(www80-non443) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is http
		if {host} starts_with www
		if {host} match (w{2,3}\.)(.*)
		/ https://{$2}
	}
}

(non80-non443) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is http
		if {host} not_starts_with www
		if {host} not_match (w{2,3}\.)(.*)
		/ https://{host}{uri}
	}
}

(non80-www80) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is http
		if {host} not_starts_with www
		if {host} not_match (w{2,3}\.)(.*)
		/ {scheme}www.{host}{uri}
	}
}

(www80-non80) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is http
		if {host} starts_with www
		if {host} match (w{2,3}\.)(.*)
		/ {scheme}{$2}
	}
}

(non80-www443) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is http
		if {host} not_starts_with www
		if {host} not_match (w{2,3}\.)(.*)
		/ https://www.{host}{uri}
	}
}

(non443-non80) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is https
		if {host} not_starts_with www
		if {host} not_match (w{2,3}\.)(.*)
		/ https://{host}{uri}
	}
}

(www443-non80) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is https
		if {host} starts_with www
		if {host} not_match (w{2,3}\.)(.*)
		/ http://{$2}
	}
}

(www443-non443) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is https
		if {host} starts_with www
		if {host} match (w{2,3}\.)(.*)
		/ {scheme}{$2}
	}
}

(non443-www443) {
	redir 308 {
		if_op and
		if {>X-Forwarded-Proto} is https
		if {host} not_starts_with www
		if {host} not_match (w{2,3}\.)(.*)
		/ {scheme}{$2}
	}
}

Are these snippets correct?
How to test efficiently without relying on the browser?
What kind of output do I need to generate in log?

Any help will be appreciated. Thank you.

You reference {$2} a number of times, which I assume is trying to get a capture group? redir doesn’t create capture groups like a regexp rewrite does (and the syntax should be just {2}), so those will become empty placeholders.

As for testing efficiently without relying on a browser… maybe you could write a shell script to curl repeatedly?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.