Fossils are remains of organisms from millions of years ago, preserved in the rocks.
A replacement fossil is a gradual replacement by minerals. Things that don't decay easily can last a long time. Eventually, they are replaced by minerals as they decay. The fossils stay distinct inside the rock.
Cast and impression fossils happen when an organism is buried in a soft material like clay. It later hardens against the organism, leaving a cast of itself. An animal's burrow or plant's rootless traces can be preserved as casts.
Preservation happens in places where no decay occurs.
To decay, decomposers need oxygen, enough moisture, optimum temperature and pH, so decay won't take place.