The castle's history started in the Middle Ages when a chapel dedicated to Our Lady of Pena was built on the top of the hill above Sintra. According to tradition, construction occurred after an apparition of the Virgin Mary.
In 1493, John II, accompanied by his wife Leonor of Viseu, made a pilgrimage to the site to fulfill a vow. His successor, Manuel I, was also very fond of this sanctuary, and ordered the construction of a monastery on this site which was donated to the Order of Saint Jerome. For centuries Pena was a small, quiet place for meditation, housing a maximum of eighteen monks.
In the 18th century the monastery was severely damaged by lightning. However, it was the 1755 Lisbon earthquake, occurring shortly afterwards, that took the heaviest toll on the monastery, reducing it to ruins. Nonetheless, the chapel (and its works of marble and alabaster attributed to Nicolau Chanterene) escaped without significant damage.
For many decades the ruins remained untouched, but they still astonished young Prince Ferdinand. In 1838, as King consort Ferdinand II, he decided to acquire the old monastery, all of the surrounding lands, the nearby Castle of the Moors and a few other estates in the area. King Ferdinand then set out to transform the remains of the monastery into a palace that would serve as a summer residence for the Portuguese royal family. The commission for the Romantic style rebuilding was given to Lieutenant-General and mining engineer Wilhelm Ludwig von Eschwege. Eschwege, a German amateur architect, was much traveled and likely had knowledge of several castles along the Rhine river. The construction took place between 1842 and 1854, although it was almost completed in 1847: King Ferdinand and Queen Maria II intervened decisively on matters of decoration and symbolism.