TechEarl

WordPress Rewrite Rules: Query Variables and Virtual Pages

Add a WordPress rewrite rule with a registered query var, a validated handler and a deliberate status code, then extend it: add_rewrite_endpoint() sub-URLs, a template_redirect fallback router for 404s, and a checklist for rules that will not fire.

Ishan KarunaratnePublished ⏱️ 22 min readUpdated
Share thisCopied
Add a WordPress rewrite rule with query vars, add_rewrite_endpoint() sub-URLs and a 404 fallback router, plus the checklist for rules that will not fire.

To add a custom rewrite rule in WordPress, call add_rewrite_rule() on init, register its query variable with the query_vars filter, validate the value in a handler, send a deliberate HTTP status, and flush the stored rules once. This guide also covers pointing a fixed URL at another page with no redirect, add_rewrite_endpoint() sub-URLs, a fallback router for 404s you cannot enumerate, and a checklist for rules that will not fire.

php
add_action( 'init', function () {
    add_rewrite_rule(
        '^te-guide/([a-z0-9-]+)/?$',
        'index.php?te_guide=$matches[1]',
        'top'
    );
} );
add_filter( 'query_vars', function ( $vars ) {
    $vars[] = 'te_guide';
    return $vars;
} );

This registers routing syntax only. It does not create content for every matching slug or automatically authorize a private resource.

The regex, the rewrite target, and the position

The request path normally has no leading slash. ^te-guide/ reserves a literal prefix; the capture accepts a single lowercase slug; /?$ allows an optional trailing slash and prevents matching extra segments. Single-quoted PHP preserves $matches[1] for WordPress to substitute later.

'top' places the rule before core's general rules; it does not make your rule the only custom rule at that position. Register specific rules before broader ones. A broad top-level ^([^/]+)/([^/]+)/?$ can capture ordinary pages and taxonomy paths. Reserve a prefix you own instead.

The index.php?... target is an internal query, not an HTTP redirect. The URL in the browser remains unchanged.

Register the query var

Add each custom public variable through query_vars, or WordPress will discard it during request parsing. Read it with get_query_var() after parsing. Public query variables can also arrive through a query string, so validate the value rather than trusting that it necessarily came from your regex.

php
$slug = (string) get_query_var( 'te_guide', '' );

A query variable is routing input, not evidence the requested resource exists.

Multiple URL segments

For a location-based list, keep a fixed prefix and capture only the meaningful values:

php
add_action( 'init', function () {
    add_rewrite_rule(
        '^te-listings/(hotels|restaurants)/([a-z0-9-]+)/?$',
        'index.php?te_listing_type=$matches[1]&te_destination=$matches[2]',
        'top'
    );
} );
add_filter( 'query_vars', function ( $vars ) {
    $vars[] = 'te_listing_type';
    $vars[] = 'te_destination';
    return $vars;
} );

/te-listings/hotels/paris/ yields hotels and paris. The handler must still validate that destination against real supported data and construct the intended query. Do not manufacture a 200 landing page for every arbitrary string that matches the regex. Use query APIs or prepared SQL for data lookups, and escape values when rendering.

Route to existing content or custom query

When a route is another address for an existing WordPress post, use its actual post type and identity in the rewrite target where possible. WordPress can then establish the normal queried object and template behavior:

php
add_action( 'init', function () {
    add_rewrite_rule(
        '^te-article/([a-z0-9-]+)/?$',
        'index.php?post_type=post&name=$matches[1]',
        'top'
    );
} );

This is an illustration of a post-backed route. Core or an SEO plugin may redirect the alias to the post's canonical permalink. Decide whether that is the desired behavior; do not disable canonical redirects globally to make an alias stick. For a permanent public URL scheme, a registered post type's rewrite settings are often a better fit than adding parallel aliases.

For a list query, select the data explicitly rather than assuming your custom variables alter WP_Query by themselves. Restore post data after a secondary loop. A template filter only selects a file; it does not by itself validate a resource, clear a 404 flag, or change HTTP status.

Point a URL at another page without a redirect

A fixed path like /offer/ can serve the content of a different page or post while the address bar keeps saying /offer/. That is the internal-query behavior above used on purpose: no 301, no Location: header, just a 200 for the alias.

php
add_action( 'init', function () {
    // A page by ID
    add_rewrite_rule( '^offer/?$', 'index.php?page_id=123', 'top' );

    // Or a post by ID
    // add_rewrite_rule( '^deal/?$', 'index.php?p=456', 'top' );

    // Or a post/page by slug (lets WordPress resolve it)
    // add_rewrite_rule( '^deal/?$', 'index.php?pagename=spring-sale-2026', 'top' );
} );

Target by ID where you can. The ID does not change when someone renames the destination page's own slug, and decoupling the public URL from whichever page sits behind it is the whole point. Flush once after adding the rule.

If the mapping is conditional or computed, or you do not want to touch the rule cache, the request filter can swap the resolved query instead. It needs no flush, but it runs on every front-end request, so keep the match exact:

php
function te_alias_request( $query_vars ) {
    $map = array(
        'offer' => 123, // /offer/  -> page 123 (current campaign)
    );

    if ( isset( $query_vars['pagename'], $map[ $query_vars['pagename'] ] ) ) {
        $target = $map[ $query_vars['pagename'] ];
        unset( $query_vars['pagename'] );
        $query_vars['page_id'] = $target;
    }

    return $query_vars;
}
add_filter( 'request', 'te_alias_request' );

Permanent campaign URLs and retired pages

The case that earns this: ads, printed QR codes and other people's backlinks all point at /offer/, and you cannot edit any of them, but the campaign behind the URL changes every few months. Build a real page per campaign, point /offer/ at whichever is live by changing one ID, flush, and every old link shows the current offer with no redirect chain piling up over the years. The same move keeps an old, well-linked URL serving a freshly written replacement page without handing its authority to a new address.

Handle the duplicate content

The moment /offer/ serves page 123, that content lives at two URLs: the alias and page 123's own permalink. Pick the URL that should rank, make it the canonical on both, then stop the other from competing: noindex the source page if it should stay reachable for previews, or 301 the source permalink to the alias if it should not (the alias itself stays an internal rewrite). Everything in one must-use plugin at wp-content/mu-plugins/te-url-alias.php:

php
<?php
/**
 * Plugin Name: TE URL Alias
 * Plugin URI:  https://techearl.com/wordpress-add-rewrite-rule
 * Description: Serves a fixed URL with another post's content via an internal rewrite (no redirect), and manages the canonical so there is no duplicate-content fallout.
 * Version:     1.0.0
 * Author:      Ishan Karunaratne
 * Author URI:  https://techearl.com
 * License:     GPL-2.0-or-later
 * Text Domain: te-url-alias
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Edit these two: the alias path, and the post/page ID it should serve.
const TE_ALIAS_PATH = 'offer';
const TE_ALIAS_TARGET_ID = 123;

function te_alias_add_rule() {
    add_rewrite_rule(
        '^' . TE_ALIAS_PATH . '/?$',
        'index.php?page_id=' . TE_ALIAS_TARGET_ID,
        'top'
    );
}
add_action( 'init', 'te_alias_add_rule' );

function te_alias_canonical( $canonical, $post ) {
    if ( $post && TE_ALIAS_TARGET_ID === (int) $post->ID ) {
        return home_url( '/' . TE_ALIAS_PATH . '/' );
    }
    return $canonical;
}
add_filter( 'get_canonical_url', 'te_alias_canonical', 10, 2 );

// True only when the visitor asked for the alias path itself.
function te_alias_is_alias_request() {
    return isset( $GLOBALS['wp'] ) && TE_ALIAS_PATH === trim( $GLOBALS['wp']->request, '/' );
}

// Keep core from redirecting /offer/ to the target's own permalink.
function te_alias_no_canonical_redirect( $redirect_url ) {
    return te_alias_is_alias_request() ? false : $redirect_url;
}
add_filter( 'redirect_canonical', 'te_alias_no_canonical_redirect' );

// noindex the source permalink only. Both URLs query the same page ID,
// so is_page() alone would noindex the alias too.
function te_alias_robots( $robots ) {
    if ( is_page( TE_ALIAS_TARGET_ID ) && ! te_alias_is_alias_request() ) {
        $robots['noindex'] = true;
        $robots['follow']  = true;
    }
    return $robots;
}
add_filter( 'wp_robots', 'te_alias_robots' );

Two details in there are easy to get wrong. is_page( TE_ALIAS_TARGET_ID ) is true on /offer/ as well as on the page's own permalink, because both resolve to the same queried page; the noindex has to check the requested path, or the URL you want to rank gets noindex too. And core's redirect_canonical() can send a request resolved by page_id to that page's permalink; returning false from the redirect_canonical filter cancels it, so the filter does that for the alias path only.

Yoast SEO prints its own canonical tag and ignores get_canonical_url, so with Yoast filter wpseo_canonical instead. Do not set the source page to noindex in Yoast's sidebar: that setting belongs to page 123, so it would noindex the alias as well. Keep the path-checked wp_robots logic for that, applied through Yoast's wpseo_robots filter if Yoast owns the robots tag:

php
add_filter( 'wpseo_canonical', function ( $canonical ) {
    if ( is_page( 123 ) ) {
        return home_url( '/offer/' );
    }
    return $canonical;
} );

Verify that the alias is internal and serves the right body:

bash
curl -sI https://example.com/offer/
curl -s https://example.com/offer/ | grep -i "black friday"

You want HTTP/2 200 with no Location: header, and a hit on a string unique to the destination page. A 301 or 302 means something is still redirecting (an SEO plugin, an .htaccess rule, or a canonical redirect the filter above did not catch), so find it before you treat the alias as working. Then view-source /offer/ and check the <link rel="canonical"> and that there is no noindex in its robots meta, and confirm the source permalink is noindex or redirects. To re-point the alias later, change TE_ALIAS_TARGET_ID, update the canonical and noindex target with it, and flush.

Add a custom endpoint to an existing URL

When the new URL is a sub-view of something WordPress already routes, so /my-post/ should also answer at /my-post/reviews/, you do not need a regex at all. add_rewrite_endpoint() registers a trailing segment that is stitched onto the end of the rules WordPress already generates for the structure you target:

php
function te_register_reviews_endpoint() {
    add_rewrite_endpoint( 'reviews', EP_PERMALINK );
}
add_action( 'init', 'te_register_reviews_endpoint' );

After a flush, /my-post/reviews/ and /my-post/reviews/5/ resolve to the same post. The main query, the is_single() context and the queried object all behave as normal; the endpoint just rides along and exposes its value in a query var of the same name. A rewrite rule is a new sentence; an endpoint is a clause appended to sentences that already exist. Use add_rewrite_rule() when the URL has no relationship to an existing post or page, and an endpoint when it is an extension of content (a tab, an account section, a print view).

EP_* masks: where the endpoint attaches

The second argument is a bitmask of EP_* constants that scopes which URL families get the endpoint. Register the wrong one and the endpoint hangs off URLs you never request:

MaskAttaches the endpoint to
EP_PERMALINKSingle post permalinks (/my-post/reviews/)
EP_PAGESPages (/about/reviews/)
EP_ROOTThe site root (/reviews/)
EP_PERMALINK | EP_PAGESBoth single posts and pages
EP_ALLEvery place WordPress supports an endpoint

There are more (EP_CATEGORIES, EP_TAGS, EP_AUTHORS, EP_DATE, EP_SEARCH, EP_COMMENTS, EP_ATTACHMENT). They are plain integers defined in wp-includes/rewrite.php, which is why a bitwise OR combines them. I avoid EP_ALL unless I genuinely need the endpoint everywhere: it generates far more rules than necessary and makes the rule set harder to debug.

Read the endpoint value: presence, not truthiness

For /my-post/reviews/5/, get_query_var( 'reviews' ) returns '5'. For the bare /my-post/reviews/, WordPress sets the query var to an empty string, not to a missing value. An empty string is falsy in PHP, so the natural if ( get_query_var( 'reviews' ) ) guard fails exactly when the endpoint is present without a value, which is often the case you most want (think /account/orders/ with no order ID). Pass false as the default and test for presence:

php
function te_render_reviews_endpoint() {
    // false: the var was never set. '' : the endpoint is present with no value.
    if ( false === get_query_var( 'reviews', false ) ) {
        return;
    }

    // The main post is already queried; this is the post the endpoint hangs off.
    $post = get_queried_object();

    header( 'Content-Type: text/html; charset=utf-8' );
    echo '<h1>Reviews for ' . esc_html( get_the_title( $post ) ) . '</h1>';
    // ... render the reviews view ...

    exit;
}
add_action( 'template_redirect', 'te_render_reviews_endpoint' );

isset( $wp_query->query_vars['reviews'] ) is the other reliable check. Use template_redirect when you take over the whole response (JSON, a file, a stripped view) and exit. When the theme should render the page with its header, footer and styling, filter template_include instead:

php
function te_reviews_template( $template ) {
    if ( false !== get_query_var( 'reviews', false ) ) {
        $custom = locate_template( 'single-reviews.php' );
        if ( $custom ) {
            return $custom;
        }
    }
    return $template;
}
add_filter( 'template_include', 'te_reviews_template' );

Flush and test the endpoint

Endpoints follow the same flush discipline as any rule. In a regular plugin, register first, then flush, on activation only:

php
function te_flush_reviews_endpoint() {
    te_register_reviews_endpoint();
    flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'te_flush_reviews_endpoint' );

Then check the status code:

bash
curl -s -o /dev/null -w '%{http_code}\n' https://example.com/my-post/reviews/
# expect: 200

A 404 almost always means the rules were not flushed, or the mask does not cover the URL family you are testing (EP_PAGES registered, a post permalink requested). If the bare /my-post/reviews/ returns 200 but your handler does nothing, the guard is testing truthiness instead of presence.

The pattern shows up wherever a sub-view belongs to existing content. WooCommerce's My Account area is built on endpoints (/my-account/orders/, /my-account/edit-address/, /my-account/downloads/), a /my-post/print/ variant can render the same content through a stripped template, and /team-member/jane/projects/ can be one post with endpoint-driven tabs instead of duplicate pages. For JSON rather than an HTML sub-view, a REST endpoint is the cleaner tool.

Virtual page with no database post

The complete must-use plugin below owns one generated endpoint, /te-status/. It returns a small status document without requiring a wp_posts row for that URL. It still boots WordPress and its normal request lifecycle; “virtual” does not mean zero database work.

Save it as wp-content/mu-plugins/te-virtual-status.php:

php
<?php
/**
 * Plugin Name: TE Virtual Status
 * Plugin URI: https://techearl.com/wordpress-add-rewrite-rule
 * Description: One explicitly owned virtual status route.
 * Version: 2.0.0
 * Author: Ishan Karunaratne
 * Author URI: https://techearl.com
 * License: GPL-2.0-or-later
 */
defined( 'ABSPATH' ) || exit;

add_action( 'init', function () {
    add_rewrite_rule( '^te-status/?$', 'index.php?te_virtual=status', 'top' );
} );
add_filter( 'query_vars', function ( $vars ) {
    $vars[] = 'te_virtual';
    return $vars;
} );

add_action( 'template_redirect', function () {
    if ( 'status' !== get_query_var( 'te_virtual' ) ) {
        return;
    }
    // Do not serve arbitrary paths merely because a query parameter was added.
    $path = wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ), PHP_URL_PATH );
    $expected = wp_parse_url( home_url( '/te-status/' ), PHP_URL_PATH );
    if ( untrailingslashit( (string) $path ) !== untrailingslashit( (string) $expected ) ) {
        return;
    }
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    if ( ! in_array( $method, array( 'GET', 'HEAD' ), true ) ) {
        status_header( 405 );
        header( 'Allow: GET, HEAD' );
        exit;
    }
    global $wp_query;
    $wp_query->is_404 = false;
    status_header( 200 );
    nocache_headers();
    header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
    if ( 'HEAD' === $method ) {
        exit;
    }
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8">';
    echo '<title>Status</title></head><body><h1>OK</h1><p>Generated at ';
    echo esc_html( gmdate( 'c' ) );
    echo '</p></body></html>';
    exit;
}, 1 );

Priority 1 lets this exact owned handler complete before ordinary canonical redirect handling. The endpoint reports that WordPress reached this handler; it is not a comprehensive database, queue or external-service health check. Add those checks deliberately if that is what monitoring requires, and keep secrets out of the response.

Choose status codes and templates deliberately

A generated page is not automatically a 404 or automatically a valid 200. The main query, registered variables, existing content and other hooks affect that result. For an existing supported resource, send 200 before output. For a missing resource, keep or set the 404 state and send 404. Redirect only when there is a real replacement.

For a themed virtual page, validate the resource before choosing a template, set the query state/status in an earlier hook, then use template_include to return an existing absolute template path. That template must actually call the theme functions it needs; choosing it does not magically execute the_content() or emit a header/footer. If the template file is missing, fail visibly rather than returning an empty success page.

For a private report, authenticate and check capability before rendering. For JSON integrations, a REST endpoint provides request validation and response handling without recreating those facilities in a frontend route.

Catch and route 404s

When you cannot write a rewrite rule for every URL a site needs to answer (thousands of legacy slugs, identifiers that live in another table, paths generated by code you do not control), let WordPress route normally, then catch the requests that would 404. Hook template_redirect, check is_404(), and either resolve the path to content with status_header( 200 ), send a 301 with wp_safe_redirect(), or let the real 404 stand:

php
function te_route_fallback() {
    if ( ! is_404() ) {
        return;
    }

    $path = trim( wp_parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ) ?? '', '/' );

    // Legacy /team/{handle} -> canonical /profiles/{handle}
    if ( preg_match( '#^team/([a-z0-9-]+)$#', $path, $m ) ) {
        wp_safe_redirect( home_url( '/profiles/' . $m[1] . '/' ), 301 );
        exit;
    }

    // Dynamic profile handles that cannot be pre-registered as rewrite rules.
    if ( strpos( $path, 'profiles/' ) === 0 ) {
        $post = te_resolve_profile( sanitize_title( substr( $path, strlen( 'profiles/' ) ) ) );
        if ( $post ) {
            te_serve_post( $post );
        }
    }

    // Anything else: fall through to the real 404.
}
add_action( 'template_redirect', 'te_route_fallback' );

template_redirect fires after WordPress has parsed the query and decided what to show, but before it picks a template, so the conditional tags are live and is_404() is accurate (called earlier, it returns false). The developer reference warns against including an alternative template and then calling exit() inside this hook, because later template_redirect callbacks never run; swap template files with template_include. The router stays clean by reshaping the query or redirecting. Like the virtual page above, it belongs in a must-use plugin, since routing has to survive a theme switch.

Resolve a would-be 404 to real content

When the URL is legitimate but WordPress cannot map it, look the post up yourself, point the main query at it and clear the 404 flag:

php
function te_resolve_profile( $handle ) {
    if ( $handle === '' ) {
        return null;
    }

    $found = get_posts( array(
        'post_type'      => 'profile',
        'post_status'    => 'publish',
        'meta_key'       => 'legacy_handle',
        'meta_value'     => $handle,
        'posts_per_page' => 1,
        'no_found_rows'  => true,
    ) );

    return $found ? $found[0] : null;
}

function te_serve_post( $post ) {
    global $wp_query;

    $wp_query->is_404            = false;
    $wp_query->is_single         = true;
    $wp_query->is_singular       = true;
    $wp_query->queried_object    = $post;
    $wp_query->queried_object_id = $post->ID;
    $wp_query->post              = $post;
    $wp_query->posts             = array( $post );
    $wp_query->post_count        = 1;
    $wp_query->found_posts       = 1;
    $wp_query->max_num_pages     = 1;

    status_header( 200 );
    nocache_headers();
}

is_404() delegates to $wp_query->is_404(), so flipping the property and seeding post/posts makes the rest of the page load treat it as a normal singular request. status_header( 200 ) overwrites the queued 404 status line, and single-profile.php (or single.php) renders as if a rule had matched. no_found_rows => true skips the SQL_CALC_FOUND_ROWS pass a single-row lookup does not need.

For a renamed slug or a moved section, do not fake a 200: the 301 branch above sends visitors and crawlers to the canonical URL. wp_safe_redirect() validates the target against the allowed hosts, so a bug in the path-building cannot become an open redirect, and exit after a redirect is expected. Use 302 only when the destination is genuinely temporary.

Rewrite rule or fallback router

SituationReach for
The URL space is a fixed, expressible pattern (/events/:year/:slug)add_rewrite_rule() plus a query var
A new public endpoint with structured paramsadd_rewrite_rule() (or the REST API)
Slugs are dynamic, user-generated, or from an external systemFallback router on template_redirect
Legacy URLs with no consistent shapeFallback router (resolve or 301)
The rule set changes at runtimeFallback router

If you can write the rule, write the rule: it matches before the query runs and does not depend on a request 404ing first. The two combine well, rules for the patterns you know and a tight router for the long tail.

To resolve a path before the main query runs, so there is no 404 state to unwind, hook parse_request and set the query vars yourself:

php
add_action( 'parse_request', function ( $wp ) {
    $path = trim( $wp->request, '/' );

    if ( strpos( $path, 'profiles/' ) !== 0 ) {
        return;
    }

    $post = te_resolve_profile( sanitize_title( substr( $path, strlen( 'profiles/' ) ) ) );
    if ( $post ) {
        // Hand WordPress real query vars; it runs one correct query, no 404.
        $wp->query_vars = array(
            'post_type' => 'profile',
            'p'         => $post->ID,
        );
    }
} );

That is cleaner when the lookup is cheap and the matching is certain. template_redirect is more forgiving when the lookup is expensive or you only want a last resort.

Avoid hijacking real 404s and redirect loops

  • Match tightly. Guard on a prefix or strict regex that describes only the paths your router owns. A loose match "resolves" typos and probe traffic and hides real broken links. Silently swallowing every miss is worse than no router.
  • Never redirect to a URL that would 404 again. If the 301 target is unresolved, the request comes back through the same hook and loops. When unsure, resolve to content in place, which cannot loop.
  • Keep it cheap. The hook runs on every 404, including bot probes and missing assets, so do the prefix check before any database lookup.
curl showing a would-be 404 URL /legacy/1/ returning a 301 redirect to the canonical post
Real output: a would-be 404 caught and 301-redirected to the right URL.

Check the status codes with curl -I. Before the router, a would-be match returns 404; after the resolve branch it returns 200; the legacy path returns a permanent redirect:

code
curl -I https://example.com/profiles/jane-doe
HTTP/2 200
content-type: text/html; charset=UTF-8

curl -I https://example.com/team/jane-doe
HTTP/2 301
location: https://example.com/profiles/jane-doe/

If an owned path still shows 404, the prefix guard does not match the real path, a page cache is serving the pre-router response, or the identifier was sanitized differently from how it is stored.

Flush the rules once, and never on every request

WordPress stores a compiled rule map in its rewrite_rules option. After adding or changing these rules:

bash
wp rewrite flush
wp rewrite list --match=te-status/ --format=table

Settings → Permalinks → Save Changes is the manual alternative. Must-use plugins do not have an activation lifecycle, so flush manually once after deploying the file. If you remove the file, flush again after the registration code is gone.

For a normal plugin, call its named rule-registration function before flushing in the activation callback. On deactivation, remove its rule registration from the in-memory rule set before rebuilding, or perform the flush after the plugin is inactive. Do not attach flush_rewrite_rules() to every init request.

Verify it with curl

bash
curl -sS -D - https://example.com/te-status/
curl -sSI https://example.com/te-status/
curl -sSI https://example.com/te-status/extra/
curl -sSI 'https://example.com/definitely-missing/?te_virtual=status'
curl -sS -o /dev/null -w '%{http_code}\n' -X POST https://example.com/te-status/

Expect the exact route to return 200, HEAD to have no body, unknown paths to remain genuine missing pages, and POST to return 405. Also test ordinary posts, pages and taxonomy archives to catch collisions. Inspect both status and body; a visually correct page can still have the wrong status.

If the rule is absent, check plugin loading and flush the rules. If it is present but the value is empty, inspect the query-var registration. If a different rule wins, inspect ordering and the fixed prefix. The troubleshooting checklist below works through each cause, and rewrite endpoints are the better fit when adding a sub-view to an existing URL is the actual task.

WordPress rewrite rules not working

Most failures come from three causes: the rules were never flushed, the custom query var was never registered, or the regex is wrong or another rule wins first. Work through these in order, most common first.

  1. No flush. WordPress builds the full rule array once and stores it in the rewrite_rules option. Until it is rebuilt, your add_rewrite_rule() call does not exist as far as the router is concerned, and the URL returns a 404 or the front page. Run wp rewrite flush or save Settings → Permalinks.
  2. Unregistered query var. The rule appears in wp rewrite list and the regex matches, but WordPress drops any variable not on its public allow-list before your code runs. The value is parsed, then discarded, and the request falls through. This is the most common reason a correct-looking rule does nothing; add it through query_vars as shown above. The filter runs per request and needs no flush.
  3. Rule order. add_rewrite_rule() defaults to 'bottom', after all of core's rules, and WordPress stops at the first match. If a page, post or attachment rule matches first, yours never runs. Use 'top' when your pattern overlaps something core routes.
  4. Regex mistakes. Without ^, reports/([0-9]+) also matches my-old-reports/12. Without an end anchor it matches reports/12/anything/else; end with /?$. (.+) is greedy and swallows slashes, so use ([^/]+) for one segment. Escape literal dots (reports\.json).
  5. Slug collision. A published Page, post or CPT entry with the same slug as your static segment competes for the URL. With 'bottom' the Page wins; with 'top' the Page becomes unreachable. Rename one side rather than blanketing everything with 'top'. Verbose page rules on sites with many nested pages make this worse, because core generates an explicit rule per page.
  6. Flushing on every request, or never. flush_rewrite_rules() rebuilds the array from every plugin and theme and writes it to the database, so calling it on init is a real performance bug. Shipping a rule without any flush leaves it stale.
  7. A must-use plugin with an activation hook. Must-use plugins have no activation step, so a register_activation_hook() callback copied from a regular plugin never fires. Register on init, then run wp rewrite flush once after each deploy that changes the pattern.

Inspect the live rules and the matched query

Stop guessing and look at what WordPress actually has. wp rewrite list prints the live rule set in evaluation order, and --match lists every rule whose pattern matches a specific URL, in that same order, with what each rewrites to. The first row is the candidate WordPress will normally use; the matched_rule log below confirms the actual winner:

bash
wp rewrite list --format=table
wp rewrite list --match=/reports/12 --format=table

If your rule is not in the list, it was not flushed. If a different rule appears above it for your URL, that is ordering. For the runtime view, hook parse_request, which fires after the URL is matched, and log the matched rule, the rewritten query string and the surviving query vars. Packaged as a drop-in must-use plugin:

php
<?php
/**
 * Plugin Name: TE Rewrite Debug
 * Plugin URI:  https://techearl.com/wordpress-add-rewrite-rule
 * Description: Logs the matched rewrite rule, the rewritten query string, and the parsed query vars on every front-end request.
 * Version:     1.0.0
 * Author:      Ishan Karunaratne
 * Author URI:  https://techearl.com
 * License:     GPL-2.0-or-later
 * Text Domain: te-rewrite-debug
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function te_rewrite_debug_log_request( $wp ) {
    if ( is_admin() ) {
        return;
    }

    $report = array(
        'request'       => $wp->request,
        'matched_rule'  => $wp->matched_rule,
        'matched_query' => $wp->matched_query,
        'query_vars'    => $wp->query_vars,
    );

    error_log( 'te-rewrite-debug: ' . wp_json_encode( $report ) );
}
add_action( 'parse_request', 'te_rewrite_debug_log_request' );

function te_rewrite_debug_log_rules() {
    global $wp_rewrite;
    error_log( 'te-rewrite-debug rules: ' . wp_json_encode( $wp_rewrite->rules ) );
}
add_action( 'init', 'te_rewrite_debug_log_rules', 99 );

Save it as wp-content/mu-plugins/te-rewrite-debug.php, load the failing URL once with WP_DEBUG_LOG on, read wp-content/debug.log, then delete the file. If your variable is missing from query_vars, it is the unregistered query var. If matched_rule is a core rule, it is ordering. The plugin registers no rule and never flushes.

flushing the rewrite rules then confirming the custom rule is live with wp rewrite list
Real output: flush, then confirm the rule is actually registered.

Once fixed, confirm all four: wp rewrite list --match shows your rule as the first matching row, the URL returns your handler's output with the right status (a soft 404 can still render content), get_query_var() returns the captured value in template_redirect, and the debug log shows your rule as matched_rule. If it still looks stale, purge the page or object cache and test fresh HTML.

Almost always one of two things. Either the rule was never flushed, so it is not in the live rewrite_rules cache (run wp rewrite flush or save Settings, Permalinks), or the rule matches but the custom query variable is not registered, so WordPress discards the captured value and the request falls through to a 404.

Confirm which with wp rewrite list --match=/your/url: if your rule is absent, it is the flush; if it is present but the value never reaches your code, it is the query var.

No. flush_rewrite_rules() rebuilds the entire rule set and writes it to the database. Flush once, on plugin activation after registering the rule, or with wp rewrite flush after deploying a must-use plugin, never on init.

Use 'top' when your pattern overlaps something WordPress already routes. Rules are evaluated in order and the first match wins, so a 'bottom' rule (the default) can lose to a core page or post rule. A 'top' rule can shadow a real page of the same slug, so check for collisions first.

A 301 changes the URL: the browser is sent to a different address and the address bar updates. An internal rewrite keeps the URL the visitor typed and serves another page's content with a plain 200 and no Location: header. Redirect when a page has genuinely moved; rewrite when the URL must stay fixed while the content behind it changes.

It dilutes rather than penalizes: Google sees two identical pages and picks one, possibly not yours. Set the canonical on both to the URL you want to rank (get_canonical_url, or wpseo_canonical with Yoast), then noindex the source page or 301 it to the alias.

add_rewrite_rule() creates a standalone regex-to-query mapping for a URL space you own. add_rewrite_endpoint() appends a trailing segment to the rules WordPress already generates for a permalink structure, so the original post still resolves underneath and the endpoint value rides along. Use an endpoint for a tab, sub-view or account section of existing content.

That is expected. When the endpoint is in the URL with no trailing value, WordPress sets the query var to an empty string. Test for presence with false !== get_query_var( 'reviews', false ) rather than a truthy check, or the bare endpoint URL never triggers your handler.

Conditional tags only work after the main query has run. Hook template_redirect, where is_404() reflects the real result, or act earlier on parse_request by setting the query vars yourself without testing is_404() at all.

Only when the URL space cannot be expressed as a pattern up front: dynamic or user-generated slugs, identifiers stored in another system, or legacy URLs with no consistent shape. If you can write the rule, write the rule, and keep a tight 404 router for the long tail.

Sources

Authoritative references this article was fact-checked against.

TagsWordPressPHPRewrite APIPermalinksRoutingEndpointsWP-CLIDebuggingtemplate_redirectCanonical

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts