Cosmic magnification has been detected through the cross-correlation between foreground and background populations (galaxies or quasars). It has been shown that weighting each background object by its α− 1 can significantly improve the cosmic magnification measurement. Here α is the logarithmic slope of the luminosity function of background populations. However, we find that this weighting function is optimal only for sparse background populations in which intrinsic clustering is negligible with respect to shot noise. We derive the optimal weighting function for a general case, including scale-independent and scale-dependent weights. The optimal weighting function improves the signal-to-noise ratio by ∼20 per cent for a BigBOSS-like survey and the improvement can reach a factor of ∼2 for surveys with much denser background populations.