The ban is largely symbolic as France imports around 99 percent of its oil and gas, but Paris hopes the move will inspire bigger producers to follow suit.
The national assembly passed the bill by 316 votes to 69.
"France is on an unstoppable path to scrapping fossil fuels," said Nicolas Hulot, the high-profile green activist named by President Emmanuel Macron as his environment minister in May.
- France to ban licences for oil and gas exploration
- France to put a stop to fossil fuel production
- France's new 'climate plan': Sales of petrol and diesel vehicles to end by 2040
No new permits will be granted to extract fossil fuels and no existing licences will be renewed beyond 2040, when all production in mainland France and its overseas territories will stop.
France extracts the equivalent of about 815,000 tonnes of oil per year -- an amount produced in a few hours by Saudi Arabia.
But the centrist Macron has said he wants France to take the lead as a major world economy switching away from fossil fuels -- and the nuclear industry -- into renewable sources.
His government plans to stop the sale of diesel and petrol engine cars by 2040 as well.
Above all the ban will affect companies prospecting for oil in the French territory of Guyana in South America, while also banning the extraction of shale gas by any means -- its extraction by fracking was banned in 2011.
The bill includes a few exceptions to the ban, including the capturing of gas from mines, which is considered desirable for security reasons.
The extraction of fossil fuels for research purposes may also be extended beyond 2040.