From the Super Mario Wiki, the Mario encyclopedia
A Rainbow Course can only be opened by finishing a level with the last two digits of the Time Limit both being the number of the world the player is on (World Mushroom being "7", World Flower "8", and World Star "9"), which is followed by the original Super Mario Bros. "Course Clear" theme playing, along with some fireworks going off and a rainbow appearing. Then, Mario can head to the beginning of the world, where a Rainbow World course has opened up. Flying Gold Blocks do not appear in Rainbow Courses, and players are also unable to use their inventory items.
At the beginning of every Rainbow Course, Mario must enter a Pipe Cannon to be launched into a Coin Heaven-type area, which holds large amounts of coins, Roulette Coin Blocks (including a larger one with a maximum number as 100 coins, instead of 50), 10 Coins, and even a single giant coin. Some courses have a Red Coin Ring that will give the player a Gold Flower in their inventory if all Red Coins are collected. However, all Rainbow Courses are slightly different from each other. If Mario falls off the course, he will not lose a life, but it will close up and Mario must redo the method of unlocking the Rainbow Course in order to access it again.
New Super Mario Bros. 2