The photons emitted from a long, long time ago in a galaxy far, far away arrive at our planet several million or even billion years after the light was first created. So, how do we know, when we locate in our skies a galaxy that is exactly 12.71 million light-years away, information which was gathered by means of machines tracking the object, that it really is that far away, just by the light it gives out? How do we know that the photons really took that long to travel to our planet? Do photons "age" in some way that is detectable by machines?
No, photons don't age, so we have to infer the distance to the object by some other means.
Stars (etc) have an absolute brightness (how much light they give out) and an apparent brightness (how much light reaches us). More distant stars of the same absolute brightness will appear dimmer. We can easily measure the apparent brightness of a star, with a telescope. If we also know the absolute brightness we can calculate the distance.
For nearby galaxies, we can see individual stars in them. Some stars have a measurable absolute brightness. We can measure the brightness of these stars, and deduce the distance of the galaxy.
For more distant galaxies, we can wait for a supernova in the galaxy. Some types of supernova have a fixed and known absolute brightness. We can then deduce the distance of the supernova, and hence the distance of the galaxy.
For many galaxies, and other objects like quasars, the only way of measuring the distance is by redshift. E. Hubble (the man) found that more distant galaxies tended to be moving away from us faster. We can measure how fast a galaxy is moving away from us using the "Doppler effect" (the so-called "red shift"), and use this to deduce the distance to the galaxy.
So we can't tell the distance "just" from the light. It is a matter of making many careful observations