MSPs voted by 105 to 18 in favour of the Marriage and Civil Partnership (Scotland) Bill.
The Scottish government said the move was the right thing to do but Scotland's two main churches were opposed to it.
The first gay and lesbian weddings could take place this autumn.
Religious and belief bodies can "opt in" to perform same-sex marriages.
Ministers said no part of the religious community would be forced to hold such ceremonies in churches.
During a debate at Holyrood, MSPs rejected amendments which were said to provide "protection" for groups and individuals opposed to same-sex marriage.
The SNP's John Mason tabled an amendment stating that no-one could be "compelled by any means" to solemnise gay marriage, including by a contract or a legal requirement.
Mr Mason said that this was similar to a measure included in the bill passed by the UK Parliament allowing same-sex marriage in England and Wales.
Health Secretary Alex Neil insisted there were "robust protections for religious bodies and celebrants" in the bill and the amendment was unnecessary.
Mr Mason tabled further amendments, including one calling for recognition that "a belief in marriage as a voluntary union between one man and one woman to the exclusion of all others for life is a belief worthy of respect in a democratic society".
He said: "This has been the prevailing view in Scotland for centuries, and may now be considered a minority view or even old fashioned, but it is an integral tenet of faith for many Christians, Muslims and others as well as the belief of many of no faith position at all."