Primary nociceptors are the first neurons involved in the complex processing system that regulates normal and pathological pain. Because of constraints on pharmacological and electrical stimulation, noninvasive excitation and inhibition of these neurons in freely moving nontransgenic animals has not been possible. Here we use an optogenetic strategy to bidirectionally control nociceptors of nontransgenic mice. Intrasciatic nerve injection of adeno-associated viruses encoding an excitatory opsin enabled light-inducible stimulation of acute pain, place aversion and optogenetically mediated reductions in withdrawal thresholds to mechanical and thermal stimuli. In contrast, viral delivery of an inhibitory opsin enabled light-inducible inhibition of acute pain perception, and reversed mechanical allodynia and thermal hyperalgesia in a model of neuropathic pain. Light was delivered transdermally, allowing these behaviors to be induced in freely moving animals. This approach may have utility in basic and translational pain research, and enable rapid drug screening and testing of newly engineered opsins.