NEW DELHI—India’s Supreme Court ruled that gay sex isn’t a crime, providing a victory for millions who have long been exposed to harassment and discrimination in the socially conservative South Asian nation because of a colonial-era law.

A nearly 500-page document outlining the court’s decision on Thursday declared that parts of a penal code called Section 377 banning sex acts labeled “against the order of nature” were unconstitutional.

While...