Port of https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/18159
For https://gitlab.com/gitlab-org/gitlab-ce/issues/36274