Obvious, but still worth mentioning, the first best way to clean your carpet is to keep your carpet clean from the start. To do this, always take off shoes before walking onto your carpets, to help keep the dirty and grime from the outside off of your carpet. Next, when you come across stains, you’re going to want to treat them immediately, before they set in. Vacuuming is the obvious regular step to keep your carpet clean, and should be done at least once a week.
But if you do encounter a stain, you’re going to have to deal with it. First off, you’ll want to be sure that you are never rubbing a stain: usually it just presses the stain in and spreads it. Instead, blot at the stain, absorbing it. For most stains, a mixture of water and shaving cream should be a good solution: just blot it, and then afterwards wash the mixture off with a water/vinegar mix. This will usually work to help get more stains off your carpet.
When a dye is involved, you’ll want to try a mix of hydrogen peroxide and water to get it out. Testing it on a small area is critical to be sure it doesn’t damage your carpet. If it is a stain from food, often brake cleaner will do to get the stain out: it helps dissolve some of the compounds involved. Blot with the mixture, and then blot away with water.
For animal stains, which are usually accompanied by odors, enzyme products are the best way to go. A mixture of peroxide and baking soda can be a good follow up if one is needed. Always blot with water afterwards.
If you wind up with oil or grease on your carpet, these tricky stains may require a more specific product to deal with. Examples of this would be DeSolvit, Orange Clean, Simple Green, or even WD40. Blot on with the solution, wait 30 minutes, and then blot away. This can be repeated to enhance effect.
When it comes to deeper cleaning, you may need to rent a carpet cleaning device. This is for carpets that are showing signs of mattering, or deep discoloration, or for stains you’ve missed. The best advice when using these is try for single strokes with the cleaner. Try not to put pressure on the machine. When you’re done, fluff the carpet to help it dry, and keep the room ventilated. And once the entire cleaning is finished, always stay off of it until it has dried, to avoid new stains.