The bishop on b5 in the position below is not attacking White’s king and it is not attacking White’s rook. It is attacking f1, four squares away down an empty diagonal, and that is enough to make 1.O-O illegal.
8
7
2
a
e
h 1 The three squares that have to be clean
The three tinted squares are the ones that matter for O-O: where the king starts, where it passes, where it stops. Every one of them must be free of enemy attack. Swap the tints to e1, d1 and c1 and you have the rule for O-O-O.
That is the whole of it. FIDE writes the three cases in one clause (Art. 3.8), which is why so many players remember one third of it. They know you cannot castle out of check, they know you cannot castle into check, and then a bishop sits on b5 and they play O-O anyway.
In the diagram White is not in check and g1 is perfectly safe. Only the middle square is covered, and only for a moment: play a2-a4 and the bishop has to leave b5, after which short castling is back on. Or forget it and play 1.O-O-O, which is legal right now, because the bishop hits nothing on the queenside.
b1 and b8 are the exception
There is exactly one square in the whole castling rule that gets a free pass, and it is the one the rook crosses on its own.
When White castles long the rook runs a1 to d1 and passes over b1 and c1. The king only goes e1 to c1. So c1 has to be safe (the king lands there) but b1 does not, and an enemy rook on an open b-file or a bishop on the h7-b1 diagonal cannot stop the move. Black gets the same free pass on b8. This trips up more experienced players than beginners, usually because it feels as though the whole path ought to be safe.
The other free pass is the rook itself. Nothing says h1 or a1 has to be unattacked, and nothing says the rook has to be defended when it lands. The full conditions list is worth reading once for that reason alone.
Two lines to look down
Two lines, one second. Before short castling, run your eye from f1 up the a6-f1 diagonal and down the f-file. Before long castling, run it from d1 up the h5-d1 diagonal and down the d-file. Those are the routes attackers use, along with a knight on e3 or g3, which is the version that catches everyone because knights do not attack in lines.
And if you find the square covered, remember the difference between this and castling out of check: here your king is fine, so you have all the time you need. Kick the piece, block the line, or castle the other way. A few castling puzzles will train the glance until you stop having to think about it.