The law had the support of both Labour and the Liberal Democrats, Britain's two other main political parties, but damaged Cameron's standing within his own party with many of his own lawmakers criticising him for being too liberal.
His own MPs had previously twice voted against it.
After a two-hour debate, the House of Commons passed the bill, meaning it now only needs to be approved by Queen Elizabeth, a formality.
"The title of this bill might be 'Marriage', but its fabric is about freedom and respect," said Culture Secretary Maria Miller, adding that traditionalists should not feel their concept of marriage had been undermined.
"Freedom to marry regardless of sexuality or gender, but also freedom to believe that marriage should be of one man and one woman, and not be marginalised," she said.
The prime minister personally endorsed the bill to try to show his party was progressive, but that upset some Conservatives who said their Christian beliefs led them to oppose marriage other than between a man and a woman.
Gay couples may already obtain "civil partnerships", conferring the same legal rights as marriage, but campaigners say the distinction gives the impression that society considers gay relationships inferior.