How the move works
Castling is the only move in chess where two pieces move at once. The king moves two squares toward one of its rooks, and that rook jumps over the king to stand on the square the king just crossed.
Kingside castling (written O-O) puts White's king on g1 and rook on f1, or Black's king on g8 and rook on f8. Queenside castling (written O-O-O) puts White's king on c1 and rook on d1, or Black's king on c8 and rook on d8.
Under the FIDE Laws castling counts as a king move. Touch the king first and move it two squares, then move the rook with the same hand. If you touch the rook first, an arbiter can hold you to a rook move instead.
The five conditions
1. The king has never moved in this game. Moving it and moving it back still counts as having moved.
2. The rook you castle with has never moved. You can lose the right on one side and keep it on the other.
3. Every square between the king and the rook is empty. On the queenside that includes the b-file square, even though the king never touches it.
4. The king is not in check. You cannot castle out of check, but you can castle later once the check is dealt with, as long as the king itself never moved.
5. The king does not cross or land on a square attacked by an enemy piece. The rook is allowed to cross an attacked square, which is why an attack on b1 or b8 does not stop queenside castling.
When to castle
Castling does two jobs in one move: it tucks the king behind a wall of pawns and connects the rooks so they can reach the centre files. That is why most strong players castle within the first ten moves.
Delaying is reasonable when the centre is closed, when you have not yet decided which wing is safer, or when castling would walk into an attack. Castling on opposite sides usually leads to a race, with both players pushing pawns at the enemy king.
Castling in Chess960
In Chess960 the pieces on the back rank are shuffled, but castling ends with the king and rook on the same squares as in standard chess: g1 and f1, or c1 and d1. All the usual conditions apply, and every square the king and rook travel over must be empty apart from the two castling pieces themselves.