CAIRO — One day in early November, a small group of elders in a dusty town in the northern Sinai Peninsula handed over three people accused of being Islamic State militants to Egyptian security forces. It was not the first time — they had handed over at least seven other people accused of being militants in the previous few months.

Three weeks later, militants stormed a packed mosque in the town, Bir al-Abed, during Friday Prayer, killing 311 people in Egypt’s worst terrorist attack.

While the attack was rooted in rising religious tensions between the local affiliate of the Islamic State and the town’s residents, Bedouins who largely practice Sufism, a mystical school of Islam that the militant group considers heresy, the motive appears to have gone beyond the theological dispute.

It was payback, residents and officials said, for the town’s cooperation with the Egyptian military, and a bloody warning of the consequences of further cooperation.