One of the best ways is to make sure you vacuum them regularly especially if you allow shoes on , inside your home.
Another good thing to do is have a good quality door mat outside your entrances as this will catch a lot of grit and sand the real enemy of carpets.
If someone spills something on your carpet please do not panic.
Use paper towels or any absorbent material to blot the spill up imediately as you do not want it to seep into the underlay or deep into the carpet.
Then use some warm water with a dash of clear dishwashing detergent in your bucket and sponge the rest out slowly .
Change the water as it gets dirty.
Then help the spill dry with a pedestal fan blowing on the area.
Hope that has been helpful to you.