=== Redirection Manager ===
Contributors: dropndot
Tags: redirect, 301 redirect, headless, graphql, 410 gone
Requires at least: 6.3
Tested up to: 7.1
Requires PHP: 7.4
Stable tag: 3.0.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Manage redirects for classic and headless WordPress. REST API, GraphQL, Next.js/Vercel/Netlify/Nginx exports, 404 log and signed webhooks.

== Description ==

**Redirection Manager** manages redirects for both classic WordPress sites and headless setups built with Next.js, Nuxt.js, React and other JavaScript frameworks. Create and search global redirects from a clean admin screen, set per-post redirects from the editor, watch real front-end 404s, test how a URL resolves, and expose everything to your frontend over a REST API or GraphQL.

Redirects are stored in a dedicated database table and resolved early on each front-end request, with object caching for fast lookups on sites that use a persistent cache such as Redis or Memcached.

**Note:** The [WPGraphQL](https://wordpress.org/plugins/wp-graphql/) plugin is required only for the GraphQL features. Everything else works without it.

= Key Features =

**Redirect management**

* Add, edit, delete, search and filter global redirects from Tools &rarr; Redirect Manager.
* Status codes 301, 302, 307 and 308, plus 410 (Gone) and 404 (Not Found) rules.
* Redirect to a path on your site or to an external `http`/`https` URL.
* Query-string handling: pass the visitor's query string (for example UTM tags) on to the destination, ignore it, or match one exact query string.
* Self-redirect, redirect-loop and redirect-chain detection when you save.
* Sortable columns, status/needs-review filters, pagination, and bulk delete / enable / disable / status changes in a single request.
* Hit count and last-hit time per redirect (can be turned off).
* Multisite ready: network activation and new sites are set up automatically.

**Post-level redirects**

* "Redirect Settings" meta box on all public post types (posts, pages, custom post types, WooCommerce products).
* Supports 301, 302, 307, 308 and 410 at the post level.
* Automatic 301 redirect when a published post's or page's URL changes (the post itself, not its children). Manual and imported redirects are never altered.

**Headless & API**

* REST API under `/wp-json/redirection-manager/v1`: single-URL lookup, rule list, rules version, exports, a token-authenticated 404 reporting endpoint, and administrator-only management endpoints.
* `ETag` / `If-None-Match` support (HTTP 304) driven by a rules version that changes whenever a redirect changes.
* Headless 404 reporting secured with a per-site API token and rate limited.
* Exports for Next.js, Vercel, Netlify and Nginx, each with a report of the rules that format cannot express.
* HMAC-SHA256 signed webhooks when redirects change, debounced and delivered in the background with retries.

**GraphQL**

* `redirectionManager` query returns enabled global redirects (newest first) with optional `limit`/`offset` paging.
* `redirectType` and `redirectUrl` fields on all public post types.

**Monitoring & tools**

* 404 log of genuine front-end "Not Found" URLs, with bounded storage, configurable retention and redirect suggestions. Suggestions are never applied automatically.
* Redirect tester that follows rules and post-level redirects for a URL and shows each hop, loops and long chains, without requesting external sites.
* CSV import with a dry-run preview. Existing redirects are never overwritten.
* CSV export of all redirects (including hits, last hit and origin) for backup and migration.
* Automatic URL normalization for consistent matching.

= Supported redirect types =

* **301 Moved Permanently** &mdash; permanent redirect with a destination URL.
* **302 Found** &mdash; temporary redirect.
* **307 Temporary Redirect** &mdash; temporary redirect that preserves the HTTP method.
* **308 Permanent Redirect** &mdash; permanent redirect that preserves the HTTP method.
* **410 Gone** &mdash; content is permanently removed; no destination needed.
* **404 Not Found** &mdash; serves your theme's 404 page for the URL (kept for rules created in 1.0.0).

== Installation ==

1. Upload the plugin files to `/wp-content/plugins/redirection-manager`, or install the plugin through the WordPress Plugins screen.
2. Activate the plugin through the Plugins screen in WordPress.
3. (Optional) Install and activate [WPGraphQL](https://wordpress.org/plugins/wp-graphql/) if you want the GraphQL features.
4. Go to **Tools &rarr; Redirect Manager** to add and manage redirects. (The old Settings &rarr; Redirect Manager address redirects there.)
5. (Optional) Set per-post redirects from the "Redirect Settings" meta box in the post editor.

== Frequently Asked Questions ==

= How do I use the redirects on a headless frontend with GraphQL? =

Query the `redirectionManager` field to get enabled global redirects (newest first, up to 5,000 per request; use the `limit` and `offset` arguments to page through more). Each redirect exposes `id`, `sourceUrl`, `destinationUrl`, `statusCode` and `queryMode`. You can also query individual posts for the `redirectType` and `redirectUrl` fields. Fragments written against the 1.0.0 `RedirectionManager` type still work.

= How do I use the REST API from a headless frontend? =

* `GET /wp-json/redirection-manager/v1/lookup?path=/old-page/` resolves one URL exactly as the site does (post-level redirects first) and returns `matched`, `status_code`, `destination` (a path for internal targets, a full URL for external ones), `query_mode` and the matching rule or post ID.
* `GET /redirects?per_page=1000&page=1` lists enabled redirects; `GET /version` returns the current rules version.
* Every GET response carries an `ETag`; send it back as `If-None-Match` to get a `304 Not Modified` with no database work.
* `POST /404` with `path` (and an optional `referrer`) records a 404 seen by your frontend. Send the API token from Tools &rarr; Redirect Manager &rarr; Settings as `X-RM-Token: <token>` or `Authorization: Bearer <token>`.
* `POST /redirects`, `PUT`/`PATCH`/`DELETE /redirects/<id>` and `GET /redirects?status=all` require an administrator (for example via an application password).
* Read endpoints are public by default, like the GraphQL list. Enable "Require authentication for read endpoints" in Settings to require an administrator or the API token.

= Which redirects can each export format express? =

* **Next.js** and **Vercel**: 301/302/307/308, including exact query-string rules; 404 and 410 rules are not exported.
* **Netlify**: 301/302/307/308 without query-string rules.
* **Nginx**: all status codes, without query-string rules.

Every export and the Tester & Import tab list the rules that were left out and why.

= How do I verify a webhook? =

Each delivery sends `X-RM-Timestamp`, `X-RM-Delivery` and `X-RM-Signature: sha256=<hex>`, where the signature is `HMAC-SHA256` of `timestamp + "." + delivery + "." + raw body` using your signing secret. Compare in constant time, reject timestamps older than 5 minutes, and ignore delivery IDs you have already processed. Failed deliveries are retried.

= Can I redirect to another website? =

Yes. Enter a full URL starting with `https://` or `http://` as the destination. A path such as `/new-page/` redirects within your own site.

= How are query strings handled? =

A source without a query string matches any query string. New redirects pass the visitor's query string (for example `?utm_source=newsletter`) on to the destination; choose "Ignore" to drop it. Redirects created before 2.1.0 keep their previous behaviour. To match one specific query string, include it in the source, for example `/page/?id=5`.

= Can I customize the 410 page? =

Yes. Add `redirection-manager-410.php` (or `410.php`) to your theme, or use the `redirection_manager_410_template` filter.

= Is my data deleted when I deactivate or delete the plugin? =

No. Deactivating never deletes anything, and deleting the plugin keeps your redirects unless you first enable "Delete all redirect data when the plugin is uninstalled" under Tools &rarr; Redirect Manager.

= What happens to my redirects when I upgrade from 1.0.0 or 2.0.x? =

The plugin copies your redirects table to a backup table before upgrading it. Nothing is deleted. Rules that cannot be used as-is (duplicates, unsupported status codes or invalid URLs) are disabled and marked "Needs review" so you can fix them. Once everything checks out, delete the backup table from the notice on the Redirect Manager screen.

= Does it work with WooCommerce? =

Yes. The post-level redirect meta box appears on WooCommerce products, and related-content detection recognizes product URLs.

== Screenshots ==

1. The Redirects tab: add, search, filter and bulk-manage global redirects with status codes, hit counts and sortable columns.
2. The 404 Log tab: genuine front-end 404s with hit counts and suggested redirects you can create with one click.
3. The Tester & Import tab: the redirect tester showing each hop of a redirect, plus CSV import with a dry-run preview.
4. The Settings tab: analytics, 404-log retention, REST read-endpoint authentication, the per-site API token, headless exports and signed webhooks.

== Changelog ==

= 3.0.0 =
* Added: REST API (`redirection-manager/v1`) with single-URL lookup, rule list, rules version, exports and administrator management endpoints.
* Added: ETag and If-None-Match (304) support based on a rules version that also changes with post-level redirects.
* Added: Token-authenticated, rate-limited 404 reporting for headless frontends, stored in the existing 404 log.
* Added: Next.js, Vercel, Netlify and Nginx exports (REST and admin download) with a report of unsupported rules.
* Added: HMAC-SHA256 signed webhooks with timestamp and delivery ID (replay protection), debounced and sent in the background with retries.
* Added: Settings for read-endpoint authentication, API token, webhook URL and signing secret.
* No database changes. Existing AJAX, GraphQL and admin features are unchanged.

= 2.3.0 =
* Added: Hit count and last-hit time per redirect (sortable; Settings &rarr; Analytics to turn off).
* Added: 404 log (Tools &rarr; Redirect Manager &rarr; 404 Log) for genuine front-end 404s; static files, admin, AJAX, REST and GraphQL requests are excluded. One row per URL, daily cleanup, configurable retention and size limit.
* Added: Redirect suggestions for logged 404s (existing redirects, content with the same or a former slug, similar titles). Nothing is created without your action.
* Added: Redirect tester showing the matched rule, status code, destination and full chain, with loop and long-chain detection. External destinations are never requested.
* Added: CSV import with dry run. Accepts this plugin's export format or "source,destination,status" rows. Duplicates, invalid URLs and unsupported status codes are reported and skipped.
* Added: Automatic 301 redirects when a published post's or page's URL changes. Manual and imported redirects are never changed; earlier automatic redirects are pointed at the new URL to avoid chains.
* Added: Hits, last hit and origin columns in the CSV export.
* Database: adds hits/last_hit/origin columns and a 404 log table. Existing rows are not modified.

= 2.2.0 =
* Added: Bulk enable, disable and status changes; all bulk actions run through one server request (in chunks of up to 500) with per-redirect results.
* Added: Sortable columns in the redirects list.
* Added: Object caching for front-end redirect lookups, including misses, invalidated automatically whenever a redirect changes.
* Added: Multisite support for network activation, new sites and site deletion.
* Added: uninstall.php. Data is kept unless "Delete all redirect data when the plugin is uninstalled" is enabled under Tools &rarr; Redirect Manager.
* Improved: The redirects list no longer looks up related content for every row; use "Find source content" on a row instead.
* Changed: Internal code split into focused classes; public methods, hooks, AJAX actions and GraphQL fields are unchanged.

= 2.1.0 =
* Added: 302 and 307 redirects (302 rules from 1.0.0 work again) and support for legacy 404 rules.
* Added: External http/https destinations; query-string pass-through and exact query-string matching.
* Added: Server-side validation with self-redirect, loop and chain detection; runtime loop guard.
* Added: Safe, resumable database upgrades from 1.0.0 and 2.0.x with an automatic backup table; legacy, duplicate and invalid rules are kept, disabled and flagged for review instead of being dropped.
* Changed: The admin screen moved to Tools &rarr; Redirect Manager (old URL redirects).
* Changed: Saving a redirect no longer trashes content automatically; use the explicit "Trash" button instead.
* Changed: GraphQL `redirectionManager` returns enabled redirects only, capped at 5,000, with optional `limit`/`offset`; added `queryMode`; post-level fields now register on custom post types with custom GraphQL names.
* Fixed: External destinations were rewritten to local paths; query strings were corrupted or dropped.
* Fixed: Sub-directory installs stripped the wrong prefix (for example /blogging/ became /ging/).
* Fixed: Upgrades from 1.0.0 failed to save or list redirects; multisite sites without the table now get one automatically.
* Fixed: Percent-encoded and non-ASCII URLs, CSV export sort order, precise error messages, status badges and pagination input.
* Security: Stricter escaping in the admin table, capability checks for trashing content, CSV formula neutralization.
* Improved: All admin strings are translatable; assets are versioned for cache busting; 410 page can be overridden by themes.

= 2.0.2 =
* Hardened redirect list queries to use fully prepared SQL and satisfy Plugin Check DirectDB requirements.

= 2.0.1 =
* Resolved an issue affecting the filter options.

= 2.0.0 =
* Major update: complete rewrite with enhanced features.
* Added support for 301 (Moved Permanently) and 308 (Permanent Redirect) redirects.
* Added support for the 410 (Gone) status code.
* Introduced post-level redirect meta boxes for all public post types.
* Added CSV export for backup and migration.
* Implemented an advanced URL normalization system.
* Added related-content detection (posts, pages, terms, WooCommerce products) and content trash management.
* Enhanced GraphQL integration with post-level fields.
* Improved the admin interface with search, filtering and pagination.
* Improved the database schema with indexes for better performance.
* Added a custom 410 error-page template and better AJAX error messages.

= 1.0.0 =
* Initial release.
* Basic redirect manager in the WordPress admin.
* Redirects stored in a custom database table.
* AJAX handling for adding and deleting redirects.
* Support for 302 redirects and 404 closures.

== Upgrade Notice ==

= 3.0.0 =
Adds a REST API, headless exports, ETags, token-secured 404 reporting and signed webhooks. No database changes; existing features are unchanged.

= 2.3.0 =
Adds redirect hit counts, a 404 log with suggestions, a redirect tester, CSV import and automatic redirects for changed post URLs. The database upgrade only adds columns and a table; existing redirects are not changed.

= 2.2.0 =
Faster redirect lookups with object caching, bulk enable/disable/status changes, sortable columns and multisite support. No database changes.

= 2.1.0 =
Fixes external and query-string redirects and adds 302/307. Your redirects table is backed up automatically before the database upgrade; nothing is deleted. The admin screen moves to Tools &rarr; Redirect Manager.

= 2.0.2 =
Security-hardening update for admin redirect list database queries. Recommended for all users.

= 2.0.0 =
Major update with new redirect types (301, 308, 410), post-level redirects, CSV export, content management features and enhanced GraphQL integration.

= 1.0.0 =
Initial version.
