BMW 528 rear headlight problem

I have a 1997 car that the rear lights constantly go in and out of operation. It happens on both driver and passenger side. Do I need to replace the whole light box, or get new circuits panels? At a loss on what to do. Any experience with this?

I would look for wiring problems, short circuits, and/or poor electrical connections before I started replacing things.