WordPress首页重定向至指定页面失效问题排查求助
Let's walk through the issues with your current code and get that redirect working reliably.
1. The URL Comparison Is Wrong
Your $GetURL variable includes the full protocol (http:// or https://), but you're comparing it to 'www.mywebsite.com'—which doesn't include the protocol. That means the condition $GetURL === 'www.mywebsite.com' will never be true. For example, if your site uses HTTPS, $GetURL will be https://www.mywebsite.com, which doesn't match your target string at all.
2. Missing Protocol in the Location Header
Even if the condition did trigger, your redirect URL (www.mywebsite.com/home) doesn't include http:// or https://. Browsers will interpret this as a relative path instead of an absolute URL, leading to broken or unexpected redirects.
3. Output Before the Header Call
PHP's header() function requires that no output is sent to the browser before it runs. If your header.php file has any spaces, HTML tags, or echo statements before this script, the redirect will fail silently (you'll see a warning in your PHP error logs if debugging is enabled).
Fixed Redirect Code
Here's a revised version of your script that addresses all these issues:
// Check if we're on the root domain (empty path or just "/") $requestPath = trim($_SERVER['REQUEST_URI'], '/'); if (empty($requestPath)) { // Determine the current protocol (http/https) $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'; // Build the full, valid redirect URL $redirectUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/home'; // Send a permanent (301) redirect header (better for SEO) header("Location: $redirectUrl", true, 301); // Stop script execution to prevent any further output exit; }
Why This Works:
- Checks the request path instead of full URL: This avoids issues with protocol differences or domain capitalization.
- Includes the protocol in the redirect: Ensures browsers interpret it as an absolute URL.
- Uses a 301 status code: Tells search engines this is a permanent redirect, which is better for SEO.
- Adds
exit: Prevents any subsequent code from running and breaking the redirect.
Other Possible Issues to Check
- Browser caching: Your browser might have cached old redirect behavior. Test in incognito/private mode or clear your browser cache.
- Server configuration conflicts: If you're using Apache, check your
.htaccessfile for existing redirect rules. For Nginx, look at your server block config—these might override your PHP script. - Plugin residue: Even if you disabled the problematic plugin, it might have left behind configuration changes (like in
.htaccess). Double-check your server config files for unexpected rules.
内容的提问来源于stack exchange,提问作者Goga Lo

