Preheat the oven to 400°F. Cut 4 slices of thick-cut bacon into small pieces and cook in a skillet over medium heat for 8–10 minutes, until browned and crisp. Drain on a paper towel-lined plate.
Peel 5 large onions and cut them in half from top to bottom. Slice them into ½-inch thick pieces, keeping the layers together. Arrange the onions evenly in a 9x13-inch baking dish.
In a bowl, combine 4 ounces softened cream cheese, 1 stick melted butter, and ⅓ cup whole milk. Stir until smooth, then mix in 1 teaspoon black pepper, a small pinch of salt, cooked bacon, and drained pimentos if using.
Spread the creamy mixture evenly over the onions without stirring it in.
Cover the dish tightly with foil and bake at 400°F for 30 minutes, until the onions are tender.
Remove the foil and sprinkle 1 to 1½ cups grated cheese over the top. Bake uncovered for another 5 minutes, until the cheese is melted and bubbly.
Let the casserole rest for a few minutes before serving.