New Zealand has banned most foreigners from buying homes as it tries to tackle runaway housing prices.

Previously the housing market was open to investors worldwide, but the government on Wednesday passed legislation that allows only New Zealand residents to buy homes.

In recent years, there have been many anecdotal stories of wealthy foreigners from Silicon Valley and beyond buying ranches in picturesque rural New Zealand as a "bolt hole" or escape option from a turbulent world.

There have also been stories of wealthy Chinese buyers outbidding New Zealanders on suburban homes in the main city of Auckland.

Statistics indicate about 3 percent of New Zealand homes are being sold to foreigners, but the amount rises to 5 percent in the scenic Queenstown region and 22 percent in central Auckland.

Last month, the directors of the International Monetary Fund executive board said they encouraged New Zealand to reconsider the ban, which they thought would be unlikely to improve housing affordability.

But the government says there is no doubt that foreigners are driving up prices, and the only question that remains is by how much. The new law fulfils a campaign pledge by the liberal-led government which came to power last year.