Url rewrite problem

I have set up docker infrastructure with LAMP and nextcloud 16 and 17 installed. Based on the domains Apache is redirecting request to specific directory what produces 500 error in nextcloud.log (not in apache):

The error message is:

{“reqId”:“3Kfv593PUs4Kc43ybuXH”,“level”:3,“time”:“2019-10-23T16:09:02+00:00”,“remoteAddr”:“172.18.0.2”,“user”:"–",“app”:“index”,“method”:“GET”,“url”:"/index.php",“message”:{“Exception”:“Exception”,“Message”:“The requested uri(/) cannot be processed by the script ‘/domains/nextcloud.domain.com/index.php’)”,“Code”:0,“Trace”:[{“file”:"/www/apps/nextcloud-16.0.5/lib/base.php",“line”:918,“function”:“getRawPathInfo”,“class”:“OC\AppFramework\Http\Request”,“type”:"->",“args”:[]},{“file”:"/www/apps/nextcloud-16.0.5/index.php",“line”:42,“function”:“handleRequest”,“class”:“OC”,“type”:"::",“args”:[]}],“File”:"/www/apps/nextcloud-16.0.5/lib/private/AppFramework/Http/Request.php",“Line”:780,“CustomMessage”:"–"},“userAgent”:“Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36”,“version”:“16.0.5.1”}

My rewrite rule in .htaccess:

RewriteCond %{HTTP_HOST} ^(.+)$
RewriteCond %{REQUEST_URI} !^/domains/ [NC]
RewriteRule ^(.*)$ domains/%1/$1 [L]

I do not quite understand your rewrite rules, but maybe this helps:

In my opinion the problem is rather related to cookie.
Nextcloud sets cookie path as path=/domains/nextcloud.xxxx.com what can make a problem with authentication. The path argument should be set to ‘/’.

There is no problem with setup/installation and geting the site with long url (without rewrite).

I have made some investigation. It seems that the problem is that OC is referencing to env SCRIPT_NAME which is different after translation by mod_rewrite.
Finally the function getRawPathInfo() is checking if path from SCRIPT_NAME is equal with URi. If not the exception is thrown.

How can I address this issue ?