This is called a phosphene — the experience of perceiving light in the visual cortex without light actually entering the eye. This commonly happens due to stimulation of the retinal ganglion cells by something else. The most frequent source in normal individuals is pressure to the retina (e.g. rubbing a closed eye.) It is also possible for phosphenes to occur due to neuronal stimulation at the cortical level. Most people have had the experience of “seeing stars” when you stand up too quickly. This happens because orthostatic hypotension results in transiently decreased cerebral perfusion; it is the metabolic shift in oxygenation and/or glucose delivery to cortical neurons that causes the perception of light. Something similar occurs with brief rises in intracranial pressure that occurs with sneezing or coughing.* Magnetic stimuli can also induce this phenomenon.
Phosphenes can also be pathologic (i.e. disease-associated). Migraine headache sufferers may experience a visual “aura” prior to a headache, which is a type of phosphene, likely mediated at the cortical level. There is some evidence to suggest that preventing the phosphene may also reduce headache frequency. Other conditions associated with phosphenes include abnormalities of the optic nerve** and retina — just as stimulation of a peripheral somatic sensory nerve might cause a pain signal to arrive in the brain in the absence of true tactile stimulation, disorders of the optic nerve can generate disorganized signals that the brain perceives as light.
*Increased intracranial pressure leads to decreased perfusion due to the differential between peripheral and cerebral pressures.
**If you read nothing else linked to this question, take a look at that paper (free in PMC). It describes optic neuropathy associated with auditory-evoked phosphenes. The patients perceived sound as light!