A central goal of ecology is to explain the diversity of coexisting species. Analogously, fundamental questions in epidemiology center around coexistence in pathogen communities. Classical models of strain competition predict variable coexistence dynamics depending upon the strength of cross-immunity. However, heterogeneity among human hosts, through variation in population structure and immune responses, can also profoundly affect coexistence. This dissertation investigates the intersection of immune-mediated competition and host heterogeneity to explain the dynamics of pathogen diversity in two viral communities: human papillomavirus (HPV) and influenza A viruses. We test hypotheses about viral dynamics by fitting mechanistic models to longitudinal data. We show that the prevalence and coexistence of over 200 genetically distinct HPV types are maintained by recurring infection within individuals of type-specific highrisk subpopulations. We then show that the dynamics of immune protection after influenza infection differ between children and adults, signaling substantial variability in the population-level selective pressures that shape the diversity of influenza strains.