About ten per cent of ‘massive’ stars (those of more than 1.5 solar masses) have strong, large-scale surface magnetic fields1,2,3. It has been suggested that merging of main-sequence and pre-main-sequence stars could produce such strong fields4,5, and the predicted fraction of merged massive stars is also about ten per cent6,7. The merger hypothesis is further supported by a lack of magnetic stars in close binaries8,9, which is as expected if mergers produce magnetic stars. Here we report three-dimensional magnetohydrodynamical simulations of the coalescence of two massive stars and follow the evolution of the merged product. Strong magnetic fields are produced in the simulations, and the merged star rejuvenates such that it appears younger and bluer than other coeval stars. This can explain the properties of the magnetic ‘blue straggler’ star τ Sco in the Upper Scorpius association that has an observationally inferred, apparent age of less than five million years, which is less than half the age of its birth association10. Such massive blue straggler stars seem likely to be progenitors of magnetars, perhaps giving rise to some of the enigmatic fast radio bursts observed11, and their supernovae may be affected by their strong magnetic fields12.