How to redirect for Next.js middleware sub-directory?

I would like to redirect users in my middleware. However, Next.js middleware behaves inconsistently. If I place the middleware in /pages/_middleware.ts the redirect will work. If I place it in /pages/api/_middleware.ts the redirect will not work.

// /pages/_middleware.ts
export function middleware() {
  return NextResponse.redirect(
    `http://example.com`
  );
}
// /pages/api/_middleware.ts
export function middleware() {
  return NextResponse.redirect(
    `http://example.com`
  );
}