First you need to configure the server to accept any subdomain for the example.com domain and redirect it to your virtual host, which should also accept any subdomain. After that, you can use the following rule to rewrite this subdomain inside a folder with the same name:
RewriteEngine on RewriteCond %{HTTP_HOST} !^www\. RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$ RewriteRule ^ %1%{REQUEST_URI} [L]
Gumbo source share