Rava teaches that we are commanded to place the mezuzah on the doorpost facing the public domain within the tefah – the handbreadth – closest to the outside.
In discussing why this is the requirement, the Rabanan say that it is simply so that the mezuzah will be reached immediately upon entering a house. Rabbi Hanina of Sura suggested that it is so that it will protect the entire house. In this context, the Gemara quotes the following in the name of Rabbi Hanina:
Come and see how the character of the Holy One, blessed be He, differs from that of men of flesh and blood. According to human standards, the king dwells within, and his servants keep guard on him from without; but with the Holy One, blessed be He, it is not so, for it is His servants that dwell within and He keeps guard over them from without; as it is said, The Lord is thy keeper; the Lord is thy shade upon thy right hand (Tehillim 121:5).
What is this protection?
Rashi says that it protects the inhabitants of the home from destructive forces.
The idea that the mezuzah offers protection to the inhabitants is found in the Talmud and Midrashim, and it has a source in the Torah itself. When the Children of Israel were leaving Egypt, they placed the blood of the Passover sacrifice on the doorposts of their homes, an act that protected them from the destructive angel who was carrying out the Plague of the Firstborn (see Sefer Shemot 12:23). Furthermore, the commandment of mezuzah closes with a promise that fulfillment of this mitzvah will offer “long life to you and to your children.” We therefore find ancient traditions that connect mezuzah with protection, and that people included the names of angels with the parchment. Still the Tur and others rule that the commandment must be fulfilled for itself and not with the intention of gaining such protection.
In a strongly worded statement, the Rambam objects to treating the commandment of mezuzah as an amulet (see Hilkhot Tefillin 5:4), and he argues that the “protection” that it offers is that it serves as a reminder of God’s presence and uniqueness, and as such, a reminder that keeps a person from sin.