diff --git a/app/helpers/gitlab_markdown_helper.rb b/app/helpers/gitlab_markdown_helper.rb
index 2d226adb2a495b19a1d02f64e8cb4244b9d93e2b..b8891d801aaed42dcdb193e04c470409ae495cde 100644
--- a/app/helpers/gitlab_markdown_helper.rb
+++ b/app/helpers/gitlab_markdown_helper.rb
@@ -102,6 +102,8 @@ def rebuild_path(path)
     path.gsub!(/(#.*)/, "")
     id = $1 || ""
     file_path = relative_file_path(path)
+    file_path = sanitize_slashes(file_path)
+
     [
       Gitlab.config.gitlab.relative_url_root,
       @project.path_with_namespace,
@@ -110,6 +112,12 @@ def rebuild_path(path)
     ].compact.join("/").gsub(/^\/*|\/*$/, '') + id
   end
 
+  def sanitize_slashes(path)
+    path[0] = "" if path.start_with?("/")
+    path.chop if path.end_with?("/")
+    path
+  end
+
   def relative_file_path(path)
     requested_path = @path
     nested_path = build_nested_path(path, requested_path)