Castling tucks the king away to safety and brings a rook into the game, all in one move. The king steps two squares toward one of its rooks, and that rook jumps over the king to land on the square right beside it.
How it works
There are two ways to castle, one toward each rook.
Short castling, toward the rook on the king's side: the white king goes from e1 to g1 and the rook from h1 to f1. It is written O-O.
Long castling, toward the rook on the queen's side: the white king goes from e1 to c1 and the rook from a1 to d1. It is written O-O-O.
Black castles the same way along the eighth rank, the king going from e8 to g8 or to c8. Castling counts as one move, a move of the king.
8
7
6
5
4
3
2
1a
b
c
d
e
f
g
h
Nothing stands between the king and either rook, and none of them has moved, so besides its ordinary steps the king has both castling squares, g1 and c1.
8
7
6
5
4
3
2
1a
b
c
d
e
f
g
h
After short castling: the king on g1, tucked in behind its pawns, and the rook on f1, ready to join the game.
When you may castle
All five of these must be true:
The king has not moved yet in this game.
The rook you castle with has not moved yet in this game.
Every square between the king and that rook is empty.
The king is not in check. You cannot castle out of check.
The king does not pass over a square an enemy piece attacks, and does not land on one. You cannot castle through check or into check.
The first two last the whole game. Once the king has moved it can never castle, even if it walks back home, and once a rook has moved, castling on that side is gone for good. The last three only count at the moment you castle: if the king is in check now, or a square is covered now, it may still castle later, once that has changed.
8
7
6
5
4
3
2
1a
b
c
d
e
f
g
h
The bishop on c4 covers f1, the square the king would pass over, so White cannot castle short here, even though neither piece has moved.
What does not stop castling
An attacked square that only the rook crosses. Only the king's path matters. In long castling the rook passes over b1 (b8 for Black), and that square must be empty, but it does not matter if an enemy piece attacks it.
A rook under attack. The rook may castle even if it is attacked.
A check that is over. A king that was in check earlier and got out of it without moving keeps its right to castle.