Answer by Adriana Heguy:

The gut microbiota, which is the community of commensal bacteria that live in our intestines, plays a role in immune system function and is currently a very active field of study. Diet and other environmental factors influence the composition of the microbiota. The intestinal microbiota produces vitamins and  process nutrients, which in turn affect immune function.

One example is short-chain fatty acids (SCFAs) which are produced by bacterial fermentation  of macronutrients, such as plant Polysaccharide. Humans do not have genes encoding the many enzyme types necessary to process these polysaccharides, which are present in plant fiber, but the bacteria in our microbiome produce the necessary enzymes. The amount of fiber  in the diet affects the composition of the microbiota ( Short chain fatty acids are not only nutritionally valuable as sources of energy but they also affect immune responses and promote the integrity of the intestinal epithelial barrier, preventing inflammation. So eat your greens, plenty of them.

However, how exactly diet affects the microbiome is still under investigation, therefore it is not possible to dictate the "perfect" diet at this point, plus they are bound to be individual genetic, epigenetic and environmental influences that determine the best diet for a given individual. It is clear that both undernutrition and overnutrition affect the microbiome's relationship with the immune system negatively.

Here is a fairly recent comprehensive review of how the gut microbiota and the host immune system interplay (technical): Page on (it could be behind a pay firewall). The field changes very rapidly, and it's actually fascinating stuff. If you're into this sort of things, follow this field, but as usual beware of sensationalistic claims.

Ian york already gave good advice: eat a balanced diet, including plenty of vegetables and fruits; avoid processed foods and under-eating and over-eating.

What are the best foods for strengthening your immune system?