Totally legal, as long as whatever you're forbidding isn't a protected class (race, gender, etc.—the details vary by jurisdiction), or, to some degree, a pretense for one.
A real-life example comes via a feud between two artists: Stuart Semple and Anish Kapoor. For reasons that are not particularly relevant to this explanation (other than perhaps that they are unrelated to Kapoor's membership in any protected class), Semple strongly dislikes Kapoor, and has made one of his products available to purchase...as long as the purchaser agrees that they are not Anish Kapoor, that they are not an associate of Anish Kapoor, and that they do not have any reason to believe that the product they are purchasing will make its way to Anish Kapoor.
The product page contains the following terms to accomplish this:
Note: By adding this product to your cart you confirm that you are not Anish Kapoor, you are in no way affiliated to Anish Kapoor, you are not purchasing this item on behalf of Anish Kapoor or an associate of Anish Kapoor. To the best of your knowledge, information and belief this paint will not make its way into the hands of Anish Kapoor.