301 Redirect everything to another domain, except for a subdomain

apache-2.4mod-rewrite

I am trying to redirect:

domain.com and www.domain.com
to
https://www.newdomain.com with a 301 redirect, except for subdomain.domain.com.

I tried different methods but these are not working. I am guessing because my subdomains physical path is under httpdocs/subdomain/ of the host (e.g. domain.com/subdomain/)

In addition, I would like for www.domain.com/subdomain/ to have its own .htaccess with fully working mod_rewrite. Is it possible? How?

Best Answer

In addition, I would like for www.domain.com/subdomain/ to have its own .htaccess with fully working mod_rewrite. Is it possible? How?

Yes, this is possible. You simply do as you suggest and include a .htaccess file in the /subdomain subdirectory. .htaccess files work along the filesystem path.

By default, mod_rewrite directives completely override any mod_rewrite directives in a parent config file, they are not inherited. So, if you include mod_rewrite directives in the subdomain's .htaccess file, this actually makes your earlier redirect easier - there is now no need to include any special conditions (RewriteCond directives). It can be simplified to just a single directive. For example:

RewriteRule (.*) https://www.newdomain.com/$1 [R=301,L]

(This does assume that newdomain.com is hosted externally.)

By accessing the subdomain, the mod_rewrite directives in the /subdomain subdirectory are processed and the redirect in the root .htaccess file is completely ignored.

Related Topic