Optimization of the Rayleigh anomaly of metallic gratings for terahertz sensor applications