为何header('Location: ../abc.php')无效,绝对路径写法可正常跳转?
header('Location:') Hey there! Let's dig into why your header('Location: ../abc.php') isn't working, while the full absolute URL does. This is a super common pitfall with PHP's redirect function, so you're not alone here.
The Main Culprits
Working Directory Mismatch
PHP resolves relative paths based on the current working directory of the script when it runs, not the directory where the script file is stored. For example:- If your script lives in
/public_html/sub/script.php, but it's being included from/public_html/index.php, the working directory is still/public_html/, so../would try to jump to/(above the document root) instead of/public_html/. The absolute URL skips this ambiguity by pointing directly to the right location.
- If your script lives in
Server Rewrite Rules or Configuration
If your server uses.htaccessrewrite rules (like for pretty URLs) or has certain configuration tweaks, the request's path context can get messed up. For instance, if all requests are routed throughindex.php, relative paths will be parsed relative toindex.php's location, not your original script. Absolute URLs bypass this confusion entirely.HTTP Compatibility Quirks
While the HTTP spec technically allows relative URLs in theLocationheader, some older browsers or server setups don't handle them consistently. Absolute URLs are universally supported, so they eliminate any parsing weirdness on the client or server side.
Fixes You Can Try
Use Root-Relative Paths
Instead of relying on../, start your path with a slash to reference from the server's document root. For example:header('Location: /folder_name/abc.php');This works no matter where your script is located, since it always points to the same spot relative to the root of your website.
Build Paths Using Script's Real Location
Use PHP's magic constants to get your script's actual directory, then construct the correct path:// Get the directory of the current script $current_dir = __DIR__; // Build the path to abc.php $target_path = realpath($current_dir . '/../abc.php'); // Convert to a root-relative URL $root_relative = '/' . ltrim(str_replace($_SERVER['DOCUMENT_ROOT'], '', $target_path), '/'); header('Location: ' . $root_relative);Stick to Absolute URLs (Most Reliable)
For foolproof redirects, build the full URL using server variables:$host = $_SERVER['HTTP_HOST']; header("Location: http://$host/folder_name/abc.php");This ensures the redirect works regardless of server configuration or script execution context.
内容的提问来源于stack exchange,提问作者Mahesh Kumar




