The Ravens (1-5) trailed 16-6 at the half, and it was 19-6 Niners (2-4) after a 42-yard Phil Dawson field goal with 7:34 to go in the third quarter. Flacco connected with Steve Smith Sr. on a 34-yard touchdown pass with 2:29 to go in the third to cut the deficit to 19-13.
Colin Kaepernick hit Quinton Patton with a 21-yard TD pass to put San Francisco back up 25-13 with 10:52 left in the fourth.
Flacco and Kamar Aiken connected on a 2-yard touchdown pass play with 5:14 to go to make it 25-20.
The Ravens had one last chance to win the game in the final seconds, but a Flacco Hail Mary into the end zone fell incomplete.
Flacco was 33-for-53 passing for 343 yards, two touchdowns and two interceptions. Justin Forsett had 62 yards rushing on 17 carries.
Smith Sr. had 137 yards on seven catches.
Kaepernick was 16-of-27 passing for 340 yards and two touchdowns with no interceptions. Anquan Boldon had five catches for 102 yards.