A virus infecting a host faces a heterogeneous and a spatially structured environment. Using a mathematical model that incorporates two types of target cells and spatial structuring, we investigate conditions for viral within-host diversification. We show that branching occurs for a wide range of parameters but that it always requires some spatial structure. Applying our model to the case of HIV, we show that it captures three main properties of the 'co-receptor switch' observed in many HIV infections: the initial dominance of virus strains that infect CCR5+ cells, the late switch in some (but, importantly, not all) HIV infections and the associated drop in the number of uninfected T-cells. This suggests that the co-receptor switch could result from gradual adaptation of the virus population to target cell heterogeneity. More generally, we argue that evolutionary ecology can help us better understand the course of some infections.