Improve middleware tests
Fix url rewriting. Close #388