Distance Between A Point And A Line.
As seen in the diagram we define a line segment to be between P1 and P2 and want to know the Point on the line segment that is closest to our point P3. We call this closest point on the line point P. An assumption is made that P1 and P2 are not co-incident (exactly the same).

We can write the Point P as

where u is a simple scaler. If we can work out u then it is easy to find P. For a line segment u must be between 0 an 1 as this keeps P between P1 and P2. If we are considering an infinite line defined by P1 and P2 then u can be any value.
The shortest distance is given when the line between P3 to P and the line p1 to p2 is perpendicular to each other. That is they have an angle of 90 degrees. The 90 degrees should give you a hint that we will need to use the dot product (inner product) to solve this problem. When the angle between two lines is 90 degree the dot product is zero. Therefor

Substitute in the value for P we obtain

Then is you site down and solve this you get

Now you know u find P is trivial.
Remember to clamp u between 0 and 1 if you are solving for the line segment rather than the infinite line case.