Search code examples
regexapache.htaccesshttp-redirecthttp-status-code-301

.htaccess redirect from old root domain to new specific sub-dir domain


RewriteEngine on  
RewriteRule ^(.*)$ http://www.NEWfoobar.com/$1 [R=301,L]  

I have this line of code from https://stackoverflow.com/a/7578810, inside .htaccess and it currently works by migrating www.OLDfoobar.com to www.NEWfoobar.com and all its sub-directory structure just fine (intended behavior, all good)

now, how do I add additional rule that captures www.OLDfoobar.com to redirect to one specific page in www.NEWfoobar.com? say for example `www.NEWfoobar.com/welcomeToNewDomain

The [L] flag is what gets me. and btw, I'm not so sure about what the $1 is for. That can't be a regex flag for the RewriteRule pattern, yes?

ACCEPTED ANSWER

RewriteEngine on  
RewriteRule ^/?$ http://www.NEWfoobar.com/some/sub/directory [R=301,L]  
RewriteRule ^(.*)$ http://www.NEWfoobar.com/$1 [R=301,L]   

Solution

  • You need

    RewriteEngine on  
    RewriteRule ^(.*)$ http://www.NEWfoobar.com/welcomeToNewDomain [R=301,L]  
    

    The $1 meant use the first capture group which is the value between the brackets on the left.

    The L in the options means stop processing the rewrite rules (ie this is the Last Rule) if the match applies.

    The ^(.*)$ means:

    `^` match beginning of string
    `(.*)` match zero or more characters and store in capture group 1
    `$` match end of string
    

    If I've miss understood an you only want to redirect the root requests while keeping the old capture you need to add a new rule before the existing one that reads

    RewriteRule ^/?$ https://www.NEWfoobar.com/welcomeToNewDomain [R=301,L]
    

    This will match either an empty path or just /