Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 11, 23:30 UTC
caddyhttp: Compare paths w/o wildcard if prefixes differ (#7015)
* fix route sort by comparing paths without wildcard if they don't share the same prefix * sort lexically if paths have the same length
WeidiDeng committed
May 14, 2025 at 03:17 UTC
8524386737e7dcaf6ab2378e5bc9456f82b91cd1
1 file changed
+18
-1
caddyconfig/httpcaddyfile/directives.go
+18
-1
@@ -483,12 +483,29 @@ func sortRoutes(routes []ConfigValue) {
483
// we can only confidently compare path lengths if both
484
// directives have a single path to match (issue #5037)
485
if iPathLen > 0 && jPathLen > 0 {
486
+ // trim the trailing wildcard if there is one
487
+ iPathTrimmed := strings.TrimSuffix(iPM[0], "*")
488
+ jPathTrimmed := strings.TrimSuffix(jPM[0], "*")
489
+
490
// if both paths are the same except for a trailing wildcard,
491
// sort by the shorter path first (which is more specific)
488
- if strings.TrimSuffix(iPM[0], "*") == strings.TrimSuffix(jPM[0], "*") {
492
+ if iPathTrimmed == jPathTrimmed {
493
return iPathLen < jPathLen
494
}
495
496
+ // we use the trimmed length to compare the paths
497
+ // https://github.com/caddyserver/caddy/issues/7012#issuecomment-2870142195
498
+ // credit to https://github.com/Hellio404
499
+ // for sorts with many items, mixing matchers w/ and w/o wildcards will confuse the sort and result in incorrect orders
500
+ iPathLen = len(iPathTrimmed)
501
+ jPathLen = len(jPathTrimmed)
502
+
503
+ // if both paths have the same length, sort lexically
504
+ // https://github.com/caddyserver/caddy/pull/7015#issuecomment-2871993588
505
+ if iPathLen == jPathLen {
506
+ return iPathTrimmed < jPathTrimmed
507
+ }
508
+
509
// sort most-specific (longest) path first
510
return iPathLen > jPathLen
511
}