Caleb Sturgis had three field goals, including one from 21 yards with 7:41 left that gave the Chargers (2-2) the lead, but he had an eventful day with two missed extra points.
Rivers was 25 of 39 for 250 yards. Gordon had his first 100-yard game since last Oct. 29 against New England.
Rivers passed John Elway to become eighth on the all-time passing yards list.
Gordon and Austin Ekeler each caught touchdowns, the first time the Chargers have had two running backs catch touchdowns since Jessie Hester and Darren Sproles did it on Nov. 22, 2010, against Denver.
C.J. Beathard, who got the start for San Francisco (1-3) after Jimmy Garoppolo's season-ending knee injury, was 23 of 37 for 298 yards with two touchdowns and two interceptions.
The Niners got off to a strong start, taking a 17-6 lead early in the second quarter on an interception return for a touchdown and scores on two of their first three drives.
Antoine Exum put San Francisco on the board 57 seconds into the game when he picked off Rivers' pass intended for Keenan Allen and returned it 38 yards for a touchdown.
After Sturgis missed a 54-yard field goal, the Niners extended their lead to two touchdowns when Beathard threw a 2-yard score to Kendrick Bourne.
Los Angeles answered that touchdown with one of its own as Rivers found a wide-open Antonio Gates for a 5-yard score to make it 14-6 after missing the extra point.
Robbie Gould's 21-yard field goal extended the lead to 17-6 before the Chargers rallied to tie it at halftime. Rivers found Ekeler in single coverage on a go route for a 22-yard touchdown and Sturgis made a field goal from 48 yards that was set up by Desmond King's 55-yard punt return.
The Chargers scored on their first two drives of the second half to take a 26-17 lead. Gordon caught a 6-yard TD pass from Rivers and Sturgis made a 25-yard field goal. With 2:50 remaining in the third quarter, Beathard got back on track by connecting with George Kittle for an 86-yard touchdown. Gould's 33-yard field goal gave the Niners a 27-26 lead with 12:39 remaining.
The Chargers' kicking problems continued with two more missed extra points by Sturgis.
Los Angeles has missed eight PATs since the start of last season, which is the most in the league. Los Angeles has missed 10 extra points since the kick was moved back in 2015 and is one of eight teams in the league to have missed 10 or more.
Niners: Wide receiver Dante Pettis and left tackle Joe Staley suffered knee injuries. Staley's injury meant San Francisco had to reshuffle its offensive line, moving first-round pick Mike McGlinchey to left tackle and putting Garry Gilliam at right tackle.
Chargers: Wide receiver Travis Benjamin, who missed the past two games due to a foot injury, did not play during the second half. He had a catch for 2 yards.
Next week, the Chargers face the Oakland Raiders in a Sunday afternoon game.