a) Would that work, and b) would this code be an acceptable way of
doing it?
Yes.
But you should put the custom directive (the Redirect
line) above the BEGIN
marker, i.e. the # BEGIN WordPress
line, because if not, then your custom directive will be gone when the WordPress rewrite rules are flushed/regenerated.
So:
# your code here:
Redirect 301 /foo https://foo.example.com
# BEGIN WordPress
RewriteEngine On
# ... WordPress rewrite rules here.
# END WordPress
But if the subdomain is in a directory in the document root of the main domain (example.com
), then you would want to use the following which prevents foo.example.com/foo
from being redirected to foo.example
:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^foo/?$ https://foo.example.com/ [L,R=301,NC,QSA]
# BEGIN WordPress
RewriteEngine On
# ... WordPress rewrite rules here.
# END WordPress
And if you wanted to redirect anything in example.com/foo
, e.g. example.com/foo/some-file
to foo.example.com/some-file
, then you can change the above RewriteRule
line to: (i.e. You basically just need to play with the rewrite rule’s regular expression.)
RewriteRule ^f(/(.*))?$ https://foo.example.com/$2 [L,R=301,NC,QSA]