URL rewriting with PHP

URL rewriting with PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Moving Beyond Query Strings: Implementing Custom URL Rewrites in PHP

Transforming a raw query string like url.com/picture.php?id=51 into a clean, semantic path such as picture.php/Some-text-goes-here/51 is a fundamental requirement for modern web applications. While frameworks like WordPress handle this automatically through complex routing systems and .htaccess rules, implementing it in a native PHP environment requires a deliberate strategy involving server configuration and application logic. The core challenge lies not just in changing the URL string, but in ensuring the server actually parses that new path before your PHP script even begins execution.

The most robust approach relies on Apache's mod_rewrite module, which allows you to intercept incoming requests and map them to internal scripts without altering the browser's address bar. If you are running a standard LAMP stack or using cPanel, this is typically handled via an .htaccess file placed in your project root. The specific rule needed to achieve the transition from id=51 to /Some-text/51 involves two distinct patterns: one that catches the old query string format and redirects it permanently (HTTP 301), and another that defines the new structure as a catch-all route.

You would configure your .htaccess file with a rule that checks for the presence of an id parameter in the GET request. If found, it issues a redirect to the new URL structure. The critical part is preserving the original query string or extracting the ID so it can be passed as a URI segment rather than a parameter.

RewriteEngine On

# Redirect old style: picture.php?id=51
RewriteCond %{QUERY_STRING} ^id=(.+)$
RewriteRule ^picture\.php$ /picture.php/%1 [R=301,L]

# Handle new style: picture.php/Some-text-goes-here/51
RewriteRule ^picture\.php/(.+)$ picture.php?id=$1 [L,QSA]

In this configuration, the first block handles legacy links by permanently redirecting them to the new format. This ensures that existing bookmarks and search engine indices do not break while maintaining SEO value. The second block captures the dynamic content from the path and injects it into the id query parameter internally. This allows your PHP application to remain agnostic of whether the ID came from a URL path or a standard query string, simplifying your controller logic significantly.

However, relying solely on Apache directives introduces platform lock-in. If you are hosting on Nginx or a shared host where .htaccess is disabled, you must replicate this behavior using PHP's internal routing mechanisms. This involves modifying the $_SERVER['REQUEST_URI'] early in the application lifecycle or defining a custom router class that intercepts the request before the framework bootstraps.

A pure PHP implementation often looks like this:

<?php
// Check if we are handling a picture request via the new route
if (basename($_SERVER['REQUEST_URI'], '.php') === 'picture.php') {
    // Attempt to extract ID from path, fallback to query string
    $parts = explode('/', $_SERVER['REQUEST_URI']);
    $id = null;

    if (isset($parts[1]) && preg_match('/^\d+$/', $parts[1])) {
        $id = $parts[1];
    } elseif (isset($_GET['id'])) {
        $id = $_GET['id'];
    }

    if ($id) {
        // Proceed with loading the picture using $id
        renderPicture($id);
        exit;
    } else {
        http_response_code(404);
        echo 'Page not found';
    }
}

// Fallback to normal query string handling
if (isset($_GET['id'])) {
    renderPicture($_GET['id']);
} else {
    handleDefault();
}

This approach gives you full control but requires careful attention to order. Logic must execute before the framework initializes, or your custom route definitions will be overridden. Additionally, security is paramount; blindly trusting the id parameter can lead to SQL injection if not sanitized. Always validate that the extracted ID matches expected patterns before using it in database queries.

For enterprise-grade applications where maintaining separate routing files becomes unwieldy, leveraging a dedicated framework like Laravel is often the pragmatic choice. These tools abstract away the server configuration and provide a robust router out of the box, handling edge cases like trailing slashes and subdomains automatically. If you are building a larger application from scratch, understanding these underlying mechanics remains essential even if you decide to rely on such frameworks later.

Our network