Fix generating urls for routes with optional parameters and static segme...

Reopening PR #16730 against 4-1-stable
Fixes #16658

Some comment: there was a regression which I fixed by re-using some code from this commit: https://github.com/rails/rails/commit/56fee39#diff-21e794f2c40cd713168f365f876738b1R80