Patients are asked to clean their guts before major rectum and colon surgery,similar to what you do when you get a colonoscopy. Ideally that removes most if not all fecal matter and a significant portion of the bacteria.
Furthermore of course the colon is rinsed before the actual surgery and often during the surgery as well if necessary, if necessary with disinfecting solutions (but far less than one would think - it's actually important to do so to the least amount possible,see below). Additionally wound closures are done with techniques that allow extremely easy healing in the most problematic parts and often multiple sutures are made to adapt tissue borders on multiple layers and in multiple ways. And during and after the surgery strong iV antibiotics are given to prevent infection. But it's actually not a good idea to totally get rid of all bacteria. Especially the guts need a healthy bacterial flora to function and,and this is important here, to avoid "bad bacteria" to take over the space. There is more and more focus to make the right bacteria grow back on the colon/and to some extent the rectum, so there are some procedures that are now done with direct faecal transplants afterwards. Nevertheless often patients will not be allowed to eat for quite some time after an operation and are fed with intravascular solution during that time. Not a pleasant experience but sadly necessary. For more external operations (rectum) patients are also given stool softeners (medication that makes the passing of faecal matter easier) and advised to do disinfecting baths often, sometimes three times a day.
And of course the body is quite good at fighting bacteria and the colon and rectum - it is built to do so,the end of the whole "waste producing" system is outside the actual abdomen inside the pelvic sack,separated by a barrier. And the whole area is heavily supplied with blood (which is actually a good thing for infection control).
And last but not least for major operations there is always the option to create an enterostoma - an artificial opening/shortcut for people to get rid of fecal matter through it. These are usually done through the abdominal wall. After everything has healed up (usually after 6 months+x) the now healed colon and the small intestine/unaffected large intestine are connected back together and the artificial opening is closed.
(Sadly this is not always possible - then patients are getting a "Barbie Butt" - a behind without an opening. Mostly for cancer.)