In recent years, millisecond-duration radio signals originating in distant galaxies appear to have been discovered in the so-called fast radio bursts. These signals are dispersed according to a precise physical law and this dispersion is a key observable quantity, which, in tandem with a redshift measurement, can be used for fundamental physical investigations. Every fast radio burst has a dispersion measurement, but none before now have had a redshift measurement, because of the difficulty in pinpointing their celestial coordinates. Here we report the discovery of a fast radio burst and the identification of a fading radio transient lasting ~6 days after the event, which we use to identify the host galaxy; we measure the galaxy’s redshift to be z = 0.492 ± 0.008. The dispersion measure and redshift, in combination, provide a direct measurement of the cosmic density of ionized baryons in the intergalactic medium of ΩIGM = 4.9 ± 1.3 per cent, in agreement with the expectation from the Wilkinson Microwave Anisotropy Probe, and including all of the so-called ‘missing baryons’. The ~6-day radio transient is largely consistent with the radio afterglow of a short γ-ray burst, and its existence and timescale do not support progenitor models such as giant pulses from pulsars, and supernovae. This contrasts with the interpretation of another recently discovered fast radio burst, suggesting that there are at least two classes of bursts.