Find $n \times n$ matrices $A$ such that $\det A = 0$ and $\text{rank}(AB) = \text{rank}(BA)$ for any $n \times n$ matrix $B$

Here is a simple way. Suppose $A\ne 0$ and $\det A=0$. Then its null space $N(A)$ and its range $R(A)$ are both nontrivial. So we can pick any nonzero $v\in N(A)$ and $w\in R(A)$.

Choose any linear map $\mathbf{B}:\mathbb{R}^n\to N(A)\subseteq\mathbb{R}^n$ such that $\mathbf{B}w=v$, and let $B$ be its matrix. Then it is easy to verify that $AB=0$ but $BA\ne 0$.