Gerhart had TD runs of 5, 10 and 1 yards and also caught two passes for 24 yards to lead the Cardinal to their first win in the rivalry since 2003. Luck, a redshirt freshman, completed 14 of his first 17 passes before incompletions on his final three attempts.
Stanford (4-1, 3-0 Pac-10) -- trying to reach a bowl game in coach Jim Harbaugh's third season and end a seven-year postseason drought -- is off to its best five-game start since going 4-0-1 in 1995 during Tyrone Willingham's first year as coach. Stanford has matched its 4-1 start from 2001 in Willingham's final season -- the last year the school played in a bowl game, losing to Georgia Tech in the Seattle Bowl.
UCLA (3-1, 0-1) is the last Pac-10 team to lose a game this season.
Gerhart, coming off a career-high 200 yards a week earlier in a win over Washington, finished with 134 yards on 29 carries and moved into fifth place on Stanford's all-time rushing list. His 24 career rushing touchdowns are tied for third in school history.
The Bruins took a big blow when they lost free safety Rahim Moore, who began the day as the nation's leader in interceptions and passes defended, early in the second quarter with a concussion.
Moore was called for a personal foul penalty on the play for hitting Cardinal tight end Coby Fleener after a pass from Luck sailed way over Fleener's head at the 13:09 mark. Moore, a sophomore with five interceptions and nine passes defended, jarred his body when he hit Fleener.
Ryan Whalen had six catches for 118 yards for the Cardinal.
Kevin Craft was 22 of 34 for 204 yards and no touchdowns for the Bruins, who struggled all day on third-down conversions and scored their lone touchdown on Johnathan Franklin's 1-yard run with 11:08 remaining.
Craft had a 31-yard completion to Terrence Austin in the Bruins' opening drive to put them in the red zone, but they settled for a 29-yard field goal by Kai Forbath -- marking just the second time all season Stanford trailed.
That lasted all of 5:40 before Gerhart's first TD run. Stanford had only trailed for only 2 seconds through its first three games this season, and that was when the Cardinal lost in the waning moments at Wake Forest on Sept. 12.
Forbath also kicked field goals of 34 and 35 yards. Harbaugh's offense got creative, too, getting a 46-yard flea flicker from Luck to Whalen in the third quarter to set up Gerhart's third score.
Stanford kept grinding out yards and didn't punt for the first time until just before halftime. The Cardinal's first drive ended after Luck completed a pass to Chris Owusu, who fumbled after getting hit from behind by Akeem Ayers. Ayers also recovered the fumble.
Stanford defensive end Erik Lorig was limited after straining a groin during Thursday's practice.
After three straight home games, Stanford now hits the road for two at Oregon State and Arizona State.