diff -Naur a/lib/hsts.c b/lib/hsts.c
--- a/lib/hsts.c	2024-12-16 10:57:30.744550545 +0800
+++ b/lib/hsts.c	2024-12-16 11:33:39.110360993 +0800
@@ -237,11 +237,13 @@
 struct stsentry *Curl_hsts(struct hsts *h, const char *hostname,
                            bool subdomain)
 {
+  struct stsentry *bestsub = NULL;
   if(h) {
     time_t now = time(NULL);
     size_t hlen = strlen(hostname);
     struct Curl_llist_element *e;
     struct Curl_llist_element *n;
+    size_t blen = 0;
     for(e = h->list.head; e; e = n) {
       struct stsentry *sts = e->ptr;
       n = e->next;
@@ -256,15 +258,19 @@
         if(ntail < hlen) {
           size_t offs = hlen - ntail;
           if((hostname[offs-1] == '.') &&
-             Curl_strncasecompare(&hostname[offs], sts->host, ntail))
-            return sts;
+	    strncasecompare(&hostname[offs], sts->host, ntail) &&
+           (ntail > blen)) {
+            /* save the tail match with the longest tail */
+            bestsub = sts;
+            blen = ntail;
+          }
         }
       }
       if(Curl_strcasecompare(hostname, sts->host))
         return sts;
     }
   }
-  return NULL; /* no match */
+  return bestsub;
 }
 
 /*
@@ -407,7 +413,7 @@
     e = Curl_hsts(h, p, subdomain);
     if(!e)
       result = hsts_create(h, p, subdomain, expires);
-    else {
+    else if(strcasecompare(p, e->host)) {
       /* the same host name, use the largest expire time */
       if(expires > e->expires)
         e->expires = expires;