This extends further to being that often, especially in older works (to the extent that they are found in older works, of course), gay characters just aren't allowed happy endings. Even if they do end up having some kind of relationship, at least one half of the couple, often the one who was more aggressive in pursuing a relationship, thus "perverting" the other one, has to die at the end. Of course, it can also happen to gay characters who aren't in relationships, particularly if they're Psycho Lesbians or Depraved Homosexuals.
Nowadays, when opinions on sexuality have shifted somewhat, justification may be attempted via Too Good for This Sinful Earth. Sometimes it's because the Magical Queer has died in a Heroic Sacrifice so that the straights may live. Naturally, this is subject to debate.
If the characters' relationship is obscured, or plain baiting, it drastically increases their chance of survival. This may be because they are often afforded more storylines that aren't exclusively gay. One discussed issue that may contribute to so many works burying their gays is that writers struggle with how to handle them — they are often created as a flat character with "gay" as their entire characterization, so once the gay-related plots have dried out the writers will recycle this one, too. In other cases, a predominantly straight show may bring in a gay character for a Very Special Episode and don't know how to organically just write the character out once the story has been told, so kill them off instead. Additionally, if the studio or producers are looking for things to cut, the characters that viewers are supposedly less likely to associate with will go first.
The revival of mass usage of this trope in 2015/16 (especially with regards to things that happened in reality — an increase in homophobic attacks, including the Pulse nightclub shooting), particularly for female LGBT characters, sparked a lot of outrage and a pledge ("The Lexa Pledge", after a main lesbian character on The 100 that was offhandedly killed) to encourage show-runners' reconsideration if planning to implement the trope. Read a thesis written about the trope and its consequences here. It's possibly also for this reason that a small British future dystopia series was brought into the spotlight, and won two Emmys in 2017: it deconstructs the hell out of the trope.