The NYPD’s intelligence unit didn’t discriminate against Muslims with far-reaching surveillance aimed at identifying “budding terrorist conspiracies” at Newark mosques and other New Jersey locations, a federal judge ruled Thursday.

In a written decision filed in federal court in Newark, District Judge William Martini dismissed a civil-rights lawsuit brought in 2012 by eight Muslims who alleged that the NYPD’s surveillance programs were unconstitutional because they focused on religion, national origin and race.

The suit had accused the department of spying on ordinary people at several mosques, restaurants and grade schools in New Jersey since 2002.

The plaintiffs, including the former principal of a grade school for Muslim girls, “have not alleged facts from which it can be plausibly inferred that they were targeted solely because of their religion,” Martini wrote.

“The more likely explanation for the surveillance was to locate budding terrorist conspir­acies.”

The judge added, “The police could not have monitored New Jersey for Muslim terrorist activities without monitoring the Muslim community itself . . . The motive for the program was not solely to discriminate against Muslims, but to find Muslim terrorists hiding among the ordinary, law-abiding Muslims.”

The ruling also singled out The Associated Press, which sparked the suit with a series of stories based on confidential NYPD documents showing how the department sought to infiltrate dozens of mosques and Muslim student groups and investigated hundreds in New York and elsewhere.

“Nowhere in the complaint do the plaintiffs allege that they suffered harm prior to the unauthorized release of documents by The Associated Press,” Martini wrote.

“This confirms that plaintiffs’ alleged injuries flow from The Associated Press’ unauthorized disclosure of the documents. . . . The Associated Press covertly obtained the materials and published them without authorization. Thus the injury, if any existed, is not fairly traceable to the city [of New York].”

The Center for Constitutional Rights, which represented the plaintiffs, called the decision troubling.

“In addition to willfully ignoring the harm that our innocent clients suffered from the NYPD’s ­illegal spying program, by upholding the NYPD’s blunderbuss Muslim-surveillance practices, the court’s decision gives legal sanction to the targeted discrimination of Muslims anywhere and everywhere in this country, without limitation, for no other reason than their religion,” said CCR Legal Director Baher Azmy.

The city’s Law Department had no immediate comment Thursday.

Former Mayor Mike Bloomberg and former Police Commissioner Raymond Kelly had been staunch supporters of the surveillance programs, saying the efforts were needed to protect the city from terrorist attacks.

A similar lawsuit filed in federal court in Brooklyn is still pending.