It is located about 45 k northwest of the Spanish capital , Madrid , in the town of San Lorenzo de El Escorial . El Escorial is a historical residence of the king of Spain , in the town of San Lorenzo de El Escorial , about 45 kilometres ( 28 miles ) northwest of the capital , Madrid , in Spain .