An illegal immigrant from Mexico, wanted for killing a California cop earlier this week, was captured Friday while attempting to flee back across the Southern border, officials said.

Gustavo Perez Arriaga, 33, was busted in Bakersfield, Calif., on suspicion of murder following a massive two-day manhunt for the alleged cop-killer.

Authorities say he was attempting to leave the country — and under heavy surveillance — prior to his arrest.

“We were never more than a step behind this guy,” explained Sheriff Adam Christianson of the Stanislaus County Sheriff’s Department.

He told reporters that Arriaga was a known gang member who had been living in the US illegally after crossing the border in Arizona. It’s unclear when he came to the US.

“While we absolutely need to stay focused on Officer Singh’s service and sacrifice, we can’t ignore the fact that this could’ve been preventable,” Christianson said, noting how Arriaga had several run-ins with police — which couldn’t be reported to ICE on account of California’s sanctuary law.

“Under SB54 in California, based on two arrests for DUI and some other active warrants that this criminal has out there, law enforcement would’ve been prevented — prohibited — from sharing any information with ICE about this criminal gang member,” the sheriff explained.

“Ladies and gentlemen, this is not how you protect a community.”

Two other men were taken into custody Friday, including Arriaga’s brother, who allegedly lied to cops and helped him escape.

Arriaga is accused of killing Newman police officer Ronil Singh — who, like him, was an immigrant.

“He came to America with one purpose, and that was to serve this country,” said Newman Police Chief Randy Richardson, calling Singh an “American patriot.”

The 8-year veteran was on patrol Wednesday when he spotted Arriaga driving a car without a license plate. He pulled him over and began investigating whether Arriaga was drunk, prompting him to open fire and flee.

Border wall advocates, including President Trump, used the killing as justification for more preventive immigration policies.

“There is right now a full scale manhunt going on in California for an illegal immigrant accused of shooting and killing a police officer during a traffic stop,” Trump tweeted Thursday. “Time to get tough on Border Security. Build the Wall!”