Redirect to a subdirectory frontpage using without using a WP plugin- what files to edit, and how?

It sounds like every time any page is loaded, if it meets the condition, it will try to redirect. So, if you’re viewing from Japan, and you hit the top-level site, you’ll be redirected. But then when you are redirected, the header.php code once again will see that you’re viewing from Japan, and try to redirect. And so on, and so forth.

So a solution to the immediate problem would be to add a condition. Only try to redirect if the visitor is currently viewing the top-level site.

<?php
// Only if this is the top-level site
if(get_current_blog_id() == 1) {
    $a = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));
    $countrycode= $a['geoplugin_countryCode'];
    if ($countrycode=='JP'){
        header( 'Location: https://mywebsite.com/jp/' );
    exit;
    }
}
?>

However, this may not be ideal. If you have content that other visitors will be viewing on the top-level site, every time they load a page, this check is going to run and slow things down. So, it would be much better to find a way to cookie visitors and not be running server-side logic every time a page is loaded.

Also, if you’ve added this code to an existing theme’s header.php file, it’s going to be overwritten every time you update the theme. So you’ll want to create a child theme if this is still the approach you want to take.