Context. The luminosity function (LF) is a powerful statistical tool used to describe galaxies and learn about their evolution. In particular, the LFs of galaxies inside clusters allow us to better understand how galaxies evolve in these dense environments. Knowledge of the LFs of galaxies in clusters is also crucial for clusters studies in the optical and near-infrared (NIR) as they encode, along with their density profiles, most of their observational properties. However, no consensus has been reached yet about the evolution of the cluster galaxy LF with halo mass and redshift. Aims. The main goal of this study is to investigate the LF of a sample of 142 X-ray selected clusters, with spectroscopic redshift confirmation and a well defined selection function, spanning a wide redshift and mass range, and to test the LF dependence on cluster global properties, in a homogeneous and unbiased way. Methods. Our study is based on the Canada–France–Hawaii Telescope Legacy Survey (CFHTLS) photometric galaxy catalogue, associated with photometric redshifts. We constructed LFs inside a scaled radius using a selection in photometric redshift around the cluster spectroscopic redshift in order to reduce projection effects. The width of the photometric redshift selection was carefully determined to avoid biasing the LF and depended on both the cluster redshift and the galaxy magnitudes. The purity was then enhanced by applying a precise background subtraction. We constructed composite luminosity functions (CLFs) by stacking the individual LFs and studied their evolution with redshift and richness, analysing separately the brightest cluster galaxy (BCG) and non-BCG members. We fitted the dependences of the CLFs and BCG distributions parameters with redshift and richness conjointly in order to distinguish between these two effects. Results. We find that the usual photometric redshift selection methods can bias the LF estimate if the redshift and magnitude dependence of the photometric redshift quality is not taken into account. Our main findings concerning the evolution of the galaxy luminosity distribution with redshift and richness are that, in the inner region of clusters and in the redshift-mass range we probe (about 0 < z < 1 and 1013 M⊙ < M500 < 5 × 1014 M⊙), the bright part of the LF (BCG excluded) does not depend much on mass or redshift except for its amplitude, whereas the BCG luminosity increases both with redshift and richness.