magento2 – Magento URL Rewrite – Extract match string and redirect to new path

I have URL For example

mydomainname/dir1/dir2/dir3/dir4/abc.jpg

I want to redirect dynamically to all matching URL

mydomainname/dir4/abc.jpg //Want extract some part and redirect to reaming part of URL

Basic I want to extract some part of URL and redirect to remains part of URL. This should be dynamically.