This post (and the paper it references) might be interesting to you.
Basically, it describes why the notion of two masses of men with edged weapons plowing into each other and slaughtering away is likely not how ancient warfare happened. The mortality rate in engaged combat is known not to have been especially high, and unless your lines broke and fled, your odds of surviving were good.
Sure, it was more dangerous in the front ranks, but that's also where the glory was to be had.
Depending on who you're fighting, how disciplined and organized they are, what the terrain advantage looks like, and other factors, there was always a strong chance that your opponent would flee before making contact while their egress was still available.
According to the central narrative texts from classical Greece (Herodotus and Thucydides) the Spartans managed to build such a reputation for martial discipline that would-be opponents frequently hesitated to engage them on the field.
It's also worth mentioning that the highest death counts in hoplite warfare were sustained when one army or another routed from the field. In routing the phalanx loses its integrity. Even when conducting fighting retreats, such as when the Athenians abandoned the siege of Syracuse, their opponents might push them away from supply lines, gradually weakening energy and morale to the point they are forced to surrender.
But in those instances where plalanxes did make contact, well, yes, being in the front was riskiest. It's hard to put anybody/get somebody to put themselves in direct combat, no matter what century.
I think this was managed by 1.) there was opportunity for social accolade by demonstrating bravery and service to the polis. Included in this scheme are the ways which states built strong esprit-de-corps off the field (Spartan common messes, Athenian demes, etc.) 2.) being in the rearmost ranks doesn't put you in a better position if the Army collapses. 3.) Those guys in the back ranks have served in the front before, so it's just your turn. You don't want to let them down. You lose some social standing if you do. 4.) Also, ideally, you've trained for this or been in combat before and understand what to do and what will help you survive.
I see a lot of social standing and training in this answers, so a follow-up question: in the middle ages when armies had a lot of levies, why someone would get the first ranks?
Follow up to this... idk if it deserves it's own thread or not
How did people react to being put in the first wave of something that seemed like suicide in more recent wars? D-Day or any pacific theatre landing. Were there frequent cases of even draftees just saying f*** that when they got put in the first wave of a landing?