Fix unnecessary 301 canonical redirect for query string encoding
This PR fixes unnecessary 301 redirect triggered by redirect_canonical() when a query string contains a + (plus sign) instead of %20.
While both + and %20 are valid representations of a space in a query string, WordPress's redirect_canonical() logic uses rawurlencode_deep(), which strictly follows RFC 3986 (using %20). When comparing the requested URL to the canonical candidate, the mismatch in encoding triggers a redirect. This can lead to redirect loops, increased server load, and cache poisoning in environments with edge caching.
Changes
- Updated
redirect_canonical()inwp-includes/canonical.phpto normalize query string encoding before comparison. - Implemented a check that treats
+and%20as equivalent within the query string portion of the URL. - Ensures that if the only difference between the current URL and the redirect candidate is the space encoding, the redirect is suppressed.
Testing Instructions
- Set up a WordPress site with pretty permalinks enabled.
- Navigate to a URL with a plus sign in a query parameter, for example:
example.com/?s=hello+world. -
Before Patch: Observe a 301 redirect to
example.com/?s=hello%20world. - After Patch: The page should load directly without a 301 redirect.
- Verify that search results and other query-dependent pages still function correctly.
Trac ticket
- https://core.trac.wordpress.org/ticket/64376
This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.