The fez has a long and complicated history in the Middle East, Eastern Europe, and North Africa. I am not a historian and am not entirely familiar with the fez's nuances of meaning in these parts of the world. However, I do know this: for most Muslims, this hat is now politically incorrect. It is considered the hat of the oppressors. On the other hand, in Morocco the fez is a symbol of nationalism; it was worn historically as a protest against the French occupation. It is now associated with the Moroccan royal court. The King of Morocco, the royal guard, cabinet ministers, and the palace staff all wear fezzes and are the only Arab leaders to do so.
The origins of the fez, called the "tarboosh" by the Moroccans, are in dispute. Some claim that its origins are ancient Greece; others claim it comes from the Balkans. The wide acceptance of the fez stem from the Ottoman Empire extending its influence (never to Morocco however) in the early 19th Century. They insisted that their subjects modernize dress and encouraged the fez in lieu of the turban. With the dissolution of the Ottoman Empire after WWI, another move towards modernization - this time looking west - actually made the fez illegal in 1925. (Hats having this kind of power and meaning is a recurring theme in history.) Men who wore fezzes were imprisoned. When monarchies were overthrown in Iraq, Egypt, and Libya, the fez was condemned by the new regimes. Many men, for the first time, went bareheaded.
The name "fez" comes from the Moroccan city of the same name. Fez, Morocco produced the dye, made from crimson berries, to color the hat. The decline of the fez's popularity has had its effect in Morocco too. Its place is not very different from that of the top hat in the UK or USA. Unless you are dressing for a wedding or funeral, or attending an affair at the royal palace, it is unusual to see a young man wearing a fez.