Officers in Spain's north African enclave of Melilla said they avoided what would have become "a fatal accident at the port" on Sunday.
A ferry heading from Melilla to Motril in southern Spain was about to let down its ramp to allow cars on board when officers said they realized there may be someone hiding close to the ramp, according to Europa Press.
Officers then contacted the ship to tell them to stop lowering the ramp and found the man hiding within. They were able to get him out and onto land without injury.
A spokesman said the young man had probably been able to climb on board the ship from the water to hide himself inside the ramp mechanism.
Police described the stowaway as a young man from north Africa who was travelling without any identification. After ensuring that the young man was unharmed, officers deported him to Morocco under an agreement between the Spanish and Moroccan governments.
Several high profile cases have grabbed the attention of the Spanish press in recent months, highlighting the plight of migrants trying to reach Europe and the great lengths they are willing to go to.
Last month an eight-year-old boy was discovered hidden in a suitcase at a border crossing at Spain's north African enclave of Ceuta, in an attempt to reunite with his parents in Spain.
Spain's two territories in northern Africa, Ceuta and Melilla, are often where many migrants seek to cross into the country and are Europe's only land border with Africa.
The Spanish Civil Guard has also been criticized in the past for officers' harsh treatment of people trying to hop the border, especially after a video emerged of guards beating a man found climbing the fence into Melilla.
Spain has also complained about EU plans to more evenly distribute asylum seekers across the countries through a quota system, saying Spain already makes great efforts to control African migration. Tens of thousands have attempted to cross the Mediterranean Sea to reach Europe this year and many have died making the perilous journey.