Al Shabaab launched an attack on government troops on Friday evening in the Awdigle district and Mubarak village in the Lower Shabelle region, south of the capital. Clashes lasted until Saturday morning, residents said.
Rebels and government troops, which control the two places, also fought there last week.
The African Union's AMISOM peacekeeping force and Somali soldiers have pushed al Shabaab, which wants to topple the Western-backed government, into smaller pockets of territory, but the group still launches regular attacks from those areas.
"We did not sleep last night because they exchanged shells and gunfire throughout the night," resident Afrah Hussein told Reuters from Awdigle district, adding he had counted 17 dead but could not say if they were soldiers or militants.
Hassan Kassim, a resident in Mubarak village, said he saw seven killed from both sides.
Al Shabaab's military operations spokesman, Abdiasis Abu Musab, told Reuters the group's fighters had killed 25 soldiers, 18 in Awdigle and seven in Mubarak. He did not mention any al Shabaab dead.
Abdikadir Mohamed Sidi, the governor of Lower Shabelle region, told Reuters that at least 40 rebels were killed but said the commander of government forces in Awdigle, Colonel Dahir Shekaal, also died.
Al Shabaab and officials often given conflicting death tolls.
Although diplomats say al Shabaab has been pushed mainly into areas in the Galgala hills in the north and Juba Valley in south, the group has continued to launch strikes on the capital Mogadishu, as well as attack Somali and AMISOM forces.