Yamen 衙門, also written 牙門, Manchu reading yamun, was a designation of bottom-level units of administration, mostly on the district level, in late imperial China. Yet there were also yamen agencies in the central administration, the most famous of which was the Foreign Office (zongli yamen 總理衙門).
The district yamen was the place where district magistrates (zhixian 知縣) had their office and dispensed justice.
The term yamen is derived from a Tang period 唐 (618-907) designation of a great palace hall. It was also the abbreviation of the office of "general of the gate [of the] serrated [flag]" (yamen jiang 牙門將), head of the imperial bodyguard (huwei 護衛), and therefore also used for elite troops or their encampments or garrisons. This term was used in this sense from the Jin period 晉 (265-420) on. The word ya "teeth" seems to be derived from the serrated flag of the military leader of the bodyguard.
The meaning of yamen as the office of local administration first appears in the history book Beishi 北史, written during the early Tang period. The transformation of the character from 牙 to 衙 is attested in Feng Yin's 封演 (jinshi degree 756) "miscellaneous" history Fengshi wenjian ji 封氏聞見記 (chapter Gongya 公牙).