diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index cb07694aea6..73bde98b920 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -4171,6 +4171,7 @@ XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source)
 	{
 		TimeLineHistoryEntry *hent = (TimeLineHistoryEntry *) lfirst(cell);
 		TimeLineID	tli = hent->tli;
+		XLogSegNo	beginseg = 0;
 
 		if (tli < curFileTLI)
 			break;				/* don't bother looking at too-old TLIs */
@@ -4181,7 +4182,6 @@ XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source)
 		 */
 		if (hent->begin != InvalidXLogRecPtr)
 		{
-			XLogSegNo	beginseg = 0;
 
 			XLByteToSeg(hent->begin, beginseg, wal_segment_size);
 
@@ -4223,6 +4223,14 @@ XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source)
 				return fd;
 			}
 		}
+
+		/*
+		 * For segments containing known timeline switches only consider the
+		 * last timeline as redo otherwise doesn't know when to switch
+		 * timelines.
+		 */
+		if (segno == beginseg && beginseg > 0)
+			break;
 	}
 
 	/* Couldn't find it.  For simplicity, complain about front timeline */
