You can do something like the following using mod_rewrite at the top of the root .htaccess
file on the main domain:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteRule ^([^./]+)/$ https://$1.example.com/ [R=302,L]
The RewriteRule
pattern ^([^./]+)/$
matches just the first (and only) path segment, excluding files (since the pattern excludes dots). The mandatory trailing slash is excluded from the capturing subpattern. Modifying this to only match a valid subdomain pattern, as in @Stephen's answer, would be advisable.
The preceding condition (RewriteCond
directive) ensures that the request does not map to an existing directory. (I'm assuming you have valid directories that need to still function.)
$1
is a backreference to the captured path segment from the URL-path, excluding the first and trailing slash, ie. slug
in your example.
Note that this is a temporary (302) redirect. Only change it to a permanent (301) - if that is the intention - once you have confirmed that it works OK. This is to avoid any caching issues.
Examples:
Applying the above directives...
A. Request example.com/slug/
.
slug/
matches the RewriteRule
pattern ^([^./]+)/$
/slug
does not exist as a directory on the filesystem.
- Redirected to
https://slug.example.com/
. SUCCESS
B. Request example.com/directory/
.
directory/
matches the RewriteRule
pattern ^([^./]+)/$
/directory
exists as a directory on the filesystem. FAIL
C. Request example.com/directory/something
.
directory/something
does not match the RewriteRule
pattern ^([^./]+)/$
. FAIL
D. Request example.com/file.html
.
file.html
does not match the RewriteRule
pattern ^([^./]+)/$
. FAIL
E. Request example.com/slug
(no trailing slash).
slug
does not match the RewriteRule
pattern ^([^./]+)/$
. FAIL
/slug/
in the URL-path? – MrWhite Nov 25 '19 at 23:53