BOSTON — Alex Cobb was coasting along and before he knew it, he was watching the bullpen hold onto a tight victory.

Cobb took a one-hit shutout into the seventh inning before tiring, Evan Longoria hit a homer over the Green Monster completely out of Fenway Park and the Tampa Bay Rays held off the Boston Red Sox 5-4 on Friday night.

“We had an opportunity to really cave there, with things working against us,” Cobb said. “We were shooting ourselves in the foot a little bit. But to be able to get out of the funk we’re in, we’ve got to be able to win ballgames like that.”

Coming off a 3-6 homestand, the Rays rebounded with just their second win in six games in Fenway this season.

“Nice win. Never a dull moment,” Tampa Bay Manager Kevin Cash said.

Boston’s Xander Bogaerts singled to extended his hitting streak to 15 games, the majors’ current longest active streak. He had a career-best 26-gamer last year.

Cobb (3-3) gave up four runs – three earned – and three hits after getting the first out in the seventh, adding to his trouble with a throwing error. Alex Colome got the final four outs for his ninth save.

Reigning AL Cy Young Award winner Rick Porcello (2-5) gave up five runs – three earned – with seven strikeouts in six innings for his second rough outing against the Rays this season. He lost only four games last year.

“Just two innings where I didn’t make pitches with runners on base, and I ended up getting hurt by it,” Porcello said.

Trailing 5-0, the Red Sox chased Cobb and sliced the deficit to one with the help of Tampa Bay’s shoddy defense. Sandy Leon had a two-run double, Cobb fired wildly past first base, allowing a run to score, and second baseman Brad Miller was charged with two errors on one play, booting a grounder and throwing the ball away, scoring another.

“Tonight we got handcuffed for the first six innings of work, but when you think back to the period of time that you’re outlining, I think there’s been a number of positive things that continue to show through,” Red Sox Manager John Farrell said.

Tim Beckham’s two-run single had pushed the Rays ahead in the fourth – with both runs unearned after third baseman Josh Rutledge bounced a throw.

They added three runs in the fifth. Corey Dickerson had an RBI double high off the wall in center field before Longoria hit his shot over a billboard above the Monster seats, a drive estimated at 406 feet.

Porcello was tagged for eight runs in 41/3 innings in a home loss to the Rays on April 14.

NOTES: Farrell said DH Hanley Ramirez was “a little bit improved” and he’s optimistic that the slugger will be in the lineup Saturday. He left Wednesday’s game in Milwaukee with a strained right shoulder after starting at first base. … Farrell said INF Marco Hernandez (injured left shoulder) could need a procedure that would “likely” be season-ending.