diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go
index 33491ec696..bf9a448ec5 100644
--- a/routers/web/repo/commit.go
+++ b/routers/web/repo/commit.go
@@ -242,6 +242,12 @@ func FileHistory(ctx *context.Context) {
 		ctx.ServerError("CommitsByFileAndRange", err)
 		return
 	}
+
+	if len(commits) == 0 {
+		ctx.NotFound("CommitsByFileAndRange", nil)
+		return
+	}
+
 	oldestCommit := commits[len(commits)-1]
 
 	renamedFiles, err := git.GetCommitFileRenames(ctx, ctx.Repo.GitRepo.Path, oldestCommit.ID.String())
diff --git a/tests/integration/repo_test.go b/tests/integration/repo_test.go
index a61c574222..224a8e67aa 100644
--- a/tests/integration/repo_test.go
+++ b/tests/integration/repo_test.go
@@ -1022,3 +1022,21 @@ func TestRepoCodeSearchForm(t *testing.T) {
 		testSearchForm(t, true)
 	})
 }
+
+func TestFileHistoryPager(t *testing.T) {
+	defer tests.PrepareTestEnv(t)()
+
+	t.Run("Normal page number", func(t *testing.T) {
+		defer tests.PrintCurrentTest(t)()
+
+		req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master/README.md?page=1")
+		MakeRequest(t, req, http.StatusOK)
+	})
+
+	t.Run("Too high page number", func(t *testing.T) {
+		defer tests.PrintCurrentTest(t)()
+
+		req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master/README.md?page=9999")
+		MakeRequest(t, req, http.StatusNotFound)
+	})
+}