NIAMEY, Niger — Less than a year ago, the Islamic State’s ambitions in Africa seemed all but shattered. In Libya, militias assisted by U.S. Special Operations soldiers and airstrikes drove the militants from their stronghold in the city of Sirte. Hundreds of Islamic State fighters died. Others fled south toward desert hideouts.

“There were no more black flags,” recalled Claudia Gazzini, a senior Libya analyst for the International Crisis Group, describing the situation when she visited southern Libya after the militant group’s defeat in December.

But many highly trained Islamic State fighters crossed into the vast ungoverned areas of impoverished Niger, according to regional security officials and analysts. Some then flowed to zones where militants were active in Mali, Nigeria and other countries.

The fighters have helped inject new energy into a spreading Islamist militancy, creating fresh challenges for U.S. forces in the region. Few Americans knew their troops were engaged in one of the world’s most complex battlegrounds until four U.S. soldiers were killed by militants last month in a remote corner of Niger.

Instead of celebrating the defeat of a key Islamic State affiliate in Africa, the Pentagon and its allies are confronting an increasingly potent constellation of militant groups and a deepening rivalry between al-Qaeda and the Islamic State for influence and recruits.

“The big challenge is the instability in Libya,” Kalla Moutari, Niger’s minister of defense, said in an interview Wednesday. “Fighters and weapons from Libya continue to come to this part of the world because there are no controls over there.”

To gain support, Islamist militants have managed to exploit ethnic and communal tensions as well as resentment over poverty and unemployment. Complicating the efforts to defeat the militants are the weakness or repressive actions of the region’s armies, poor governance and porous borders.

The killing of the four U.S. soldiers has set off questions in Washington about the U.S. military’s role in the Sahel, a barren belt stretching from western Africa to its north-central region.

The Trump administration suspects a relatively new Islamic State ally was responsible for the American soldiers’ deaths. The U.S. government has doubled down on its military commitment in the region, the latest sign being a $60 million pledge this week to build a new counterterrorism force there.

U.S. authorities are concerned that with the Islamic State losing territory in Iraq and Syria, it is shifting more of its focus to North Africa and West Africa. Thousands of Islamic State militants who fought in Iraq, Syria and Libya are originally from this region, particularly Tunisia and Morocco.

“As they are pressed, it becomes all the more important that they seem to be visible and active elsewhere and thus still relevant to the overall cause,” said Bruce Hoffman, director of the Center for Security Studies at Georgetown University. “In their view, they want to show that they are still able to position themselves ahead of al-Qaeda in their competition and rivalry.”

Looking for a comeback

In recent months, the Islamic State, also known as ISIS, has sought to make a comeback in Libya, orchestrating suicide bombings and other violence. An Islamic State affiliate based in Egypt’s northern Sinai has killed several hundred policemen and soldiers this year. Islamic State-linked groups and cells have emerged in Algeria, Tunisia and Morocco.

Nigeria’s Boko Haram — which in 2015 pledged loyalty to the Islamic State — has expanded its reach, staging attacks in Cameroon, southern Niger and Chad. Libyan militia commanders and officials have said many West Africans fought with the Islamic State in Libya before its defeat there.

American military officials believe the Islamic State in the Greater Sahara, or ISGS, had targeted the U.S. soldiers and several of their Nigerien counterparts, even though no group has claimed responsibility. The militia, led by former al-Qaeda-linked militants, was formed in 2015. It was recognized by Islamic State leader Abu Bakr al-Baghdadi in October 2016, around the time the group was on the verge of defeat in Sirte.

This year, the ISGS has claimed several attacks in Burkina Faso as well as an attempt to free Islamist militants from a prison in Niger.

“There’s a greater environment . . . for jihadist groups to be active and operational and attempt to build up their capacities,” said Aaron Zelin, an expert on such groups at the Washington Institute for Near East Policy.

In 2007, two years after U.S. soldiers began arriving in North and West Africa to train local armies, their main terrorist threat was al-Qaeda in the Islamic Maghreb, or AQIM, a fledgling affiliate with roots in the Algerian civil war.

Four years later, Libya’s Arab Spring revolution brought down dictator Moammar Gaddafi. His regime’s destruction — brought about with the aid of NATO airstrikes — had an unexpected consequence: invigorating Islamist militants in the region.

Gaddafi’s arms depots were looted and many weapons smuggled to other countries. The arms helped fuel a 2012 rebellion by Tuareg nomads in northern Mali that was subsequently hijacked by AQIM and other militant groups. For nearly a year, the rebels controlled large portions of the area, until French forces drove them out.

AQIM and its splinter groups continued to operate in the region, attacking security forces and claiming responsibility for deadly attacks on hotels and cafes in Mali, Ivory Coast and Burkina Faso.

The al-Qaeda affiliate is now one of the best-armed and best-financed terrorist groups in the world, deriving tens of millions of dollars from kidnapping Westerners.

This year, it has expanded into new areas and bolstered its operational capacities, and several other militias in the region have united and pledged allegiance to al-Qaeda.

AQIM is also deepening its presence in Libya, seeking to take advantage of the Islamic State’s setbacks there and trying to attract departing Islamic State fighters, regional analysts said.

‘Ideological Divide’

Unlike in Syria, militants from al-Qaeda and the Islamic State seldom if ever fight each other here. There’s plenty of crossover between the two groups, and many rival fighters have known each other for years. They often operate in the same terrain.

Their differences are based less on religion or philosophy and more on the agendas of individual commanders or communities the groups represent.

“It doesn’t mean there’s not tension,” said Andrew Lebovich, a regional political and security researcher and visiting fellow at the European Council on Foreign Relations. “But it’s not just this kind of ideological divide that people often apply to ISIS versus al-Qaeda.”

The trajectory of Adnan Abu Walid al-Sahrawi illustrates the complex relationships among militant groups in the region. Believed to be in his mid-40s, the leader of ISGS was raised in Algerian refugee camps. He became a leader in the Polisario Front, a movement seeking to end Morocco’s presence in the Western Sahara. Sometime in the 1990s, he settled in Mali.

He eventually joined al-Mourabitoun, an al-Qaeda offshoot led by an Algerian, Mokhtar Belmokhtar. In 2015, Sahrawi had a falling out with him and launched the ISGS.

Its main base of operations straddles the Niger-Mali border, where the U.S. soldiers were killed.

Moutari, the Niger defense minister, said Sahwari is believed to be using weapons from Libya and fighters who were part of the Islamic State when it ruled Sirte. “There are many fighters from Libya, as well as those who fought in Syria and Iraq and later came to Libya, who have joined this group,” Moutari said.

Continuing Attacks

In Niger, one of the world’s poorest countries, there are about 800 U.S. service members — part of a contingent of 6,000 American troops on the continent. They include Special Forces soldiers who began arriving here in 2012 to provide counterterrorism training, as well as others who work on a drone base. There are also some 4,000 French troops based in the region.

Yet the attacks keep happening.

Along the long and lawless border where the U.S. soldiers died, the United Nations has documented at least 46 attacks since February 2016, mostly targeting local security forces.

The extremists have established ties in communities long neglected by the region’s weak central governments. The vacuum of authority has allowed militant groups to exploit grievances over government corruption, rampant crime and a lack of opportunities.

In many villages, the Islamist militants have caught thieves and adjudicated marital and family disputes, in effect replacing the government.

In Mali, AQIM and other Islamist militants have exploited ethnic and tribal tensions between the mostly Tuareg and Arab north and the ruling southern ethnic groups. They have also taken advantage of tensions between pastoralists and farmers over land and access to grazing.

“For these communities, a political movement, especially one promising instant answers through violence, is enormously appealing,” Georgetown’s Hoffman said.

“What we’ve learned is that these groups established a toehold in this region that they’ve turned into a foothold,” he added. “They are able to recruit fighters faster than we can train up the local host-nation security forces.”