The Slovenian veteran raced away from Enric Mas to cross the line first after the 158.7 kilometre run from Ubeda to Cazorla.
Red Bull-Bora-Hansgrohe rider Roglic delivered a tour de force on the sharp uphill finish and now trails the Australian, who came in 17th, by three minutes 49 seconds in the general classification.
"I was suffering, it was hard today, but in the end I went for it," said Roglic, who attacked three times on the tricky final climb to Cazorla.
"It was hard, hot, I was lucky I had the legs to take it today.
"We will enjoy (closing down O'Connor) but maybe I will lose again 10 seconds tomorrow."
Vuelta contender Joao Almeida dropped from third to 26th in the general classification as he struggled in the final stages, finishing four minutes 53 seconds behind Roglic.
Spaniard Mas rose to third overall, trailing Decathlon AG2R La Mondiale rider O'Connor by four minutes 31 seconds.
With attacks flying in frequently there was a rapid start to the stage, with the peloton responding well.
Eventually an eight-man breakaway formed after the 50km mark, with the peloton keeping them on a four-minute leash which they began to reel in towards the end.
Roglic attacked for the first time but O'Connor stayed with him diligently.
The chase group shut down those left in front with 1.5 kilometres remaining, during the sharp uphill finish.
Roglic took a third dig after a second attack was shut down and this time he left everyone for dead except for Movistar's Mas, whom he powered ahead of to take the stage.
On Sunday riders battle in the Sierra Nevada, travelling 178.5km from Motril to Granada in stage nine.