php redirect with HTTP query string variables

php redirect with HTTP query string variables

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Preserving Query Parameters in PHP 301 Redirects

When implementing a permanent redirect using header("Status: 301 Moved Permanently"), the default behavior of the web server is to discard the current request's query string. If your source page is example.com/page?user=123 and you issue a redirect to ./content/index.html, the resulting URL becomes simply example.com/content/index.html. The user=123 parameter vanishes.

This happens because the Location header specifies the absolute or relative target path, but it does not automatically inherit the query string from the incoming request unless explicitly told to do so. For standard HTTP clients and browsers, this is often acceptable if the new page has no state dependencies. However, in scenarios like login flows, shopping carts, or API integrations where param=blah represents critical session data, losing it breaks the user experience immediately.

To maintain the query string across a 301 redirect, you must manually construct the target URL by appending the original request's query parameters. The most robust approach in raw PHP is to utilize the $_SERVER['QUERY_STRING'] superglobal. This variable contains exactly what follows the question mark in the current URL.

Here is how you can modify your existing code block:

<?php
    // Capture the original query string if it exists
    $queryString = $_SERVER['QUERY_STRING'];
    
    // Construct the new location, preserving the query string
    $newLocation = './content/index.html';
    if ($queryString) {
        $newLocation .= '?' . $queryString;
    }

    header("Status: 301 Moved Permanently");
    header("Location: " . $newLocation);
    exit;
?>

This logic works by checking if $queryString is non-empty. If the user accessed the page without parameters, $_SERVER['QUERY_STRING'] returns an empty string, and the redirect remains clean. If parameters are present, they are concatenated to the target path before being sent in the Location header.

There is a subtle but important distinction between relative and absolute URLs here. Your original code used a relative path (./content/index.html). While this works fine if the base domain remains identical, using an absolute URL (e.g., https://example.com/content/index.html) is generally safer for 301 redirects. Relative paths can sometimes cause issues depending on how the client resolves them relative to the current document, whereas an absolute URL ensures the redirect always points to the intended resource regardless of the browser's current context.

Handling Multiple Parameters and Fragments

A common pitfall when manually constructing URLs is mishandling multiple parameters or the fragment identifier (the part after #). The $_SERVER['QUERY_STRING'] variable only contains the query string; it does not include the fragment. This is actually desirable behavior for a redirect because fragments are client-side instructions that should never be sent to the server. If you attempt to append them, they will appear in the URL but will be stripped by the browser before the request completes, potentially causing confusion if your backend logic depends on specific query structures.

If your application relies heavily on complex query strings with special characters, ensure that $_SERVER['QUERY_STRING'] is handled correctly. While PHP's superglobal usually handles URL decoding automatically for access via $_GET, the raw string in $_SERVER['QUERY_STRING'] often retains its original encoded format. This is beneficial for redirects because you want to pass the exact string back to the server as the client originally intended, preserving percent-encoded characters like %20 instead of converting them to spaces prematurely.

Laravel Considerations

If you are working within a Laravel application, the manual manipulation of headers using header() and exit is often unnecessary. Laravel's routing system handles this elegantly through the redirect() helper. By default, Laravel 5.2+ preserves the query string when redirecting unless explicitly told otherwise.

return redirect()->route('content.index', ['id' => $id])->permanent();

However, if you are performing a raw redirect to a specific path (like ./content/index.html) outside of a route definition, you can still leverage Laravel's response facade:

return response()->redirect('/content/index.html?', $_SERVER['QUERY_STRING'], 301)->send();

The second argument in the redirect helper allows you to pass the query string explicitly. Note that using response()->redirect() automatically calls exit, so you should not call header() or exit manually after this line, as it can lead to duplicate header warnings and unexpected behavior.

Security Implications

When appending $_SERVER['QUERY_STRING'] directly to a URL, you inherit the exact parameters sent by the client. While this preserves functionality, it also means you cannot sanitize the input at this layer. If your destination page expects specific parameter names but the source URL contains malicious or unexpected keys (e.g., ?admin=true&cmd=delete), blindly appending the string could bypass intended security checks if the destination page is vulnerable to injection or lacks proper input validation.

Best practice dictates that the destination endpoint should always validate and sanitize its own inputs, regardless of whether they arrive via a direct request or a redirect. However, be aware that some frameworks might treat unexpected query parameters as errors or warnings. Always test your redirect logic against various edge cases, such as empty query strings, multiple parameters, and special characters, to ensure the behavior remains consistent and secure.

Our network