Referrer would be for someone clicking from elsewhere and not the current page, so I don't think the above code would work as expected.
I would personally use .htaccess to accomplish this.
That would allow you to make it work without redirects. The ^$ in the rule means root of the domain only. I put the .* on the conditions to match domain1.com or
www.domain1.com. If it's domain1.com without the www, this would redirect. You could create 4 sets of conditions and rules if you wanted to keep that straight, too.
Brian.