如何实现HTML按钮跳转至对应语言子域名的同路径页面?
Hey there! Great question—this is a super common need for multi-language sites with mirrored page structures, and there are a couple of straightforward, reliable ways to implement this dynamic redirect.
Option 1: Pure Frontend JavaScript (Great for Static Sites)
If your site is static or you don't want to rely on backend code, you can use JavaScript to dynamically update the link's URL based on the current page. This method preserves all path details, query parameters, and even anchor tags (like #section), which is perfect for your use case.
Here's the code you can drop in:
<a id="german-switcher" href="#"><img src="images/DE.png">German</a> <script> // Grab the current page's full URL object const currentPageUrl = new URL(window.location.href); // Replace the main domain with your German subdomain currentPageUrl.hostname = 'german.hello.com'; // Update the link's href to the new German URL document.getElementById('german-switcher').href = currentPageUrl.toString(); </script>
Option 2: PHP Backend Implementation (Matches Your currentpage.php Idea)
If your site runs on PHP, you can generate the German URL server-side, which is often more reliable for dynamic content and avoids any client-side JavaScript dependencies.
Here's how to do it safely (note the htmlspecialchars to prevent XSS vulnerabilities):
<?php // Get the full request path (includes subpages, query strings, etc.) $currentRequestPath = $_SERVER['REQUEST_URI']; // Build the complete German subdomain URL $germanPageUrl = 'https://german.hello.com' . $currentRequestPath; ?> <a href="<?php echo htmlspecialchars($germanPageUrl); ?>"><img src="images/DE.png">German</a>
Quick Notes
- Both methods will automatically redirect users to the exact same page path on the German subdomain—so
hello.com/contactbecomesgerman.hello.com/contact, and evenhello.com/imprint?ref=homebecomesgerman.hello.com/imprint?ref=home. - Make sure every page on your main domain has a corresponding page on
german.hello.comto avoid 404 errors! - If you use other backend languages (like Node.js, Python, or Ruby), the logic is identical: just fetch the current request path and prepend your German subdomain.
内容的提问来源于stack exchange,提问作者M. Antony

