Pipelines are the safest and most cost-effective alternative for transporting oil and refined products. Nevertheless, accidental losses of containment (LOCs) may occur, thus posing significant threats to people and the surrounding environment. These LOCs also lead to substantial economic losses due to remediation, commodity loss, emergency response, and property damage. The effects of an LOC might be mitigated by implementing proper maintenance plans and installing sectioning valves (i.e., blocking). The location and number of sectioning valves depend on the type of pipeline (underground or non-underground), the commodity being transported, the neighboring population density, and altimetry. Therefore, defining the optimal location and number of valves in a pipeline is a challenging decision that goes beyond the static distances suggested by recognized standards such as CSA Z662. In this paper, a model is proposed to determine the optimal number and location of sectioning valves, which minimize the expected economic losses in terms of the amount of volume spilled and the costs of remediation, emergency response efforts, repair, and commodity loss. The model is applied to a real oil pipeline with significant changes in altimetry. The results indicate a reduction between 10 and 18% of the expected economic losses compared with a static distance reported by CSA Z662.