The portal protein is a key component of many double-stranded DNA viruses, governing capsid assembly and genome packaging. Twelve subunits of the portal protein define a tunnel, through which DNA is translocated into the capsid. It is unknown how the portal protein functions as a gatekeeper, preventing DNA slippage, whilst allowing its passage into the capsid, and how these processes are controlled. A cryo-EM structure of the portal protein of thermostable virus P23-45, determined in situ in its procapsid-bound state, indicates a mechanism that naturally safeguards the virus against genome loss. This occurs via an inversion of the conformation of the loops that define the constriction in the central tunnel, accompanied by a hydrophilic-hydrophobic switch. The structure also shows how translocation of DNA into the capsid could be modulated by a changing mode of protein-protein interactions between portal and capsid, across a symmetry-mismatched interface.