Giter VIP home page Giter VIP logo

10up / safe-redirect-manager Goto Github PK

View Code? Open in Web Editor NEW
304.0 57.0 82.0 2.18 MB

A simple HTTP redirection plugin for WordPress.

Home Page: https://wordpress.org/plugins/safe-redirect-manager

License: GNU General Public License v2.0

Shell 4.67% PHP 81.87% JavaScript 12.56% CSS 0.90%
http-redirects redirect-manager url-redirection safe-http-redirection multisite-redirects redirects redirect-plugins wordpress-plugin

safe-redirect-manager's Introduction

Safe Redirect Manager

A WordPress plugin to safely and easily manage your website's HTTP redirects.

Support Level E2E test PHPUnit Linting PHPCS PHPCompatibility Dependency Review Release Version WordPress tested up to version GPLv2 License

Purpose

Easily and safely manage your site's redirects the WordPress way. There are many redirect plugins available. Most of them store redirects in the options table or in custom tables. Most of them provide tons of unnecessary options. Some of them have serious performance implications (404 error logging). Safe Redirect Manager stores redirects as Custom Post Types. This makes your data portable and your website scalable. Safe Redirect Manager is built to handle enterprise level traffic and is used on major publishing websites. The plugin comes with only what you need following the WordPress mantra, decisions not options. Actions and filters make the plugin very extensible.

Installation

Install the plugin in WordPress. You can download a zip via GitHub and upload it using the WordPress plugin uploader ("Plugins" > "Add New" > "Upload Plugin").

Configuration

There are no overarching settings for this plugin. To manage redirects, navigate to the administration panel ("Tools" > "Safe Redirect Manager").

Each redirect contains a few fields that you can utilize:

"Redirect From"

This should be a path relative to the root of your WordPress installation. When someone visits your site with a path that matches this one, a redirect will occur. If your site is located at http://example.com/wp/ and you wanted to redirect http://example.com/wp/about to http://example.com, your "Redirect From" would be /about.

Clicking the "Enable Regex" checkbox allows you to use regular expressions in your path. There are many great tutorials on regular expressions.

You can also use wildcards in your "Redirect From" paths. By adding an * at the end of a URL, your redirect will match any request that starts with your "Redirect From". Wildcards support replacements. This means if you have a wildcard in your from path that matches a string, you can have that string replace a wildcard character in your "Redirect To" path. For example, if your "Redirect From" is /test/*, your "Redirect To" is http://google.com/*, and the requested path is /test/string, the user would be redirect to http://google.com/string.

"Redirect To"

This should be a path (i.e. /test) or a URL (i.e. http://example.com/wp/test). If a requested path matches "Redirect From", they will be redirected here. "Redirect To" supports wildcard and regular expression replacements.

"HTTP Status Code"

HTTP status codes are numbers that contain information about a request (i.e. whether it was successful, unauthorized, not found, etc). You should almost always use either 302 (temporarily moved) or 301 (permanently moved).

Note:

  • Redirects are cached using the Transients API. Cache busts occur when redirects are added, updated, and deleted so you shouldn't be serving stale redirects.
  • By default the plugin only allows at most 1000 redirects to prevent performance issues. There is a filter srm_max_redirects that you can utilize to up this number.
  • "Redirect From" and requested paths are case insensitive by default.
  • Developers can use srm_additional_status_codes filter to add status codes if needed.
  • Rules set with 403 and 410 status codes are handled by applying the HTTP status code and render the default WordPress wp_die screen with an optional message.
  • Rules set with a 404 status code will apply the status code and render the 404 template.
  • Browsers heavily cache 301 (permanently moved) redirects. It's recommended to test your permanent redirects using the 302 (temporarily moved) status code before changing them to 301 permanently moved.

Filters

Default redirect status code

The default redirect HTTP status code can be changed using the srm_default_direct_status filter.

add_filter(
	'srm_default_direct_status',
	/**
	 * Set the default redirect status to 301 (Moved Permanently).
	 */
	function() {
		return 301;
	}
);

Redirect loops detection

By default redirect loop detection is disabled. To prevent redirect loops you can filter srm_check_for_possible_redirect_loops.

add_filter( 'srm_check_for_possible_redirect_loops', '__return_true' );

Only redirect if 404 occurs

By default every matched URL is redirected. To only redirect matched but not found URLs (i.e., 404 pages), use srm_redirect_only_on_404.

add_filter( 'srm_redirect_only_on_404', '__return_true' );

CLI commands

The following WP-CLI commands are supported by Safe Redirect Manager:

  • wp safe-redirect-manager list

    List all of the currently configured redirects.

  • wp safe-redirect-manager create <from> <to> [<status-code>] [<enable-regex>] [<post-status>]

    Create a redirect. <from> and <to> are required parameters.

    • <from>: Redirect from path. Required.
    • <to>: Redirect to path. Required.
    • <status-code>: HTTP Status Code. Optional. Default to 302.
    • <enable-regex>: Whether to enable Regular expression. Optional. Default to false.
    • <post-status>: The status of the redirect. Optional. Default to publish.

    Example: wp safe-redirect-manager create /about-us /contact-us 301

  • wp safe-redirect-manager delete <id>

    Delete a redirect by <id>.

  • wp safe-redirect-manager update-cache

    Update the redirect cache.

  • wp safe-redirect-manager import <file> [--source=<source-column>] [--target=<target-column>] [--regex=<regex-column>] [--code=<code-column>] [--order=<order-column>]

    Imports redirects from a CSV file.

    • <file>: Path to one or more valid CSV file for import. This file should contain redirection from and to URLs, regex flag and HTTP redirection code. Here is the example table:

      source target regex code order
      /legacy-url /new-url 0 301 0
      /category-1 /new-category-slug 0 302 1
      /tes?t/[0-9]+/path/[^/]+/? /go/here 1 302 3
      ... ... ... ... ...

      You can also use exported redirects from "Redirection" plugin, which you can download here: /wp-admin/tools.php?page=redirection.php&sub=modules

    • --source: Header title for source ("from" URL) column mapping.

    • --target: Header title for target ("to" URL) column mapping.

    • --regex: Header title for regex column mapping.

    • --code: Header title for code column mapping.

    • --order: Header title for order column mapping.

  • wp safe-redirect-manager import-htaccess <file>

    Import .htaccess file redirects.

Development

Setup

Follow the configuration instructions above to setup the plugin. We recommend developing the plugin locally in an environment such as WP Local Docker.

Testing

Within the terminal change directories to the plugin folder. Initialize your unit testing environment by running the following command:

bash bin/install-wp-tests.sh database username password host version

Run the plugin tests:

phpunit

Issues

If you identify any errors or have an idea for improving the plugin, please open an issue.

Translations

Safe Redirect Manager is available in English and other languages. A listing of those languages and instructions for translating the plugin into other languages is available on Translating WordPress. Many thanks to the contributors on the translation teams!

Support Level

Stable: 10up is not planning to develop any new features for this, but will still respond to bug reports and security concerns. We welcome PRs, but any that include new features should be small and easy to integrate and should not include breaking changes. We otherwise intend to keep this tested up to the most recent version of WordPress.

Changelog

A complete listing of all notable changes to Safe Redirect Manager are documented in CHANGELOG.md.

Contributing

Please read CODE_OF_CONDUCT.md for details on our code of conduct, CONTRIBUTING.md for details on the process for submitting pull requests to us, and CREDITS.md for a listing of maintainers of, contributors to, and libraries used by Safe Redirect Manager.

Like what you see?

safe-redirect-manager's People

Contributors

amyevans avatar barryceelen avatar benoitchantre avatar bmarshall511 avatar braders avatar cmmarslender avatar danielbachhuber avatar davisshaver avatar dependabot[bot] avatar dhanendran avatar dinhtungdu avatar dkotter avatar eugene-manuilov avatar faisal-alvi avatar github-actions[bot] avatar helen avatar iamdharmesh avatar jayedul avatar jeffpaul avatar kmgalanakis avatar nateconley avatar nicholasio avatar peterwilsoncc avatar ravinderk avatar sidsector9 avatar simonwheatley avatar sksaju avatar tauno avatar tlovett1 avatar tomjn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

safe-redirect-manager's Issues

check_for_possible_redirect_loops runs in Theta( n^2 ) time

I was using this plugin on a project with ~250 redirects. I wrote an import script that made use of the create_redirect method to generate the redirects. After creating the redirects, the WordPress backend was "frozen". It seemed as though something was caught in an infinite loop.

After some searching I realized the problem was the check_for_possible_redirect_loops(). This method checks each redirect against every other redirect meaning it runs in Theta( n^2 ) time where n is the number of redirects. With 250 redirects, the contents of the loop in that function will be executed over 62,000 times.

Proposal: Add another filter "max_redirects_to_check_for_loops" or something to that effect. It should default to 50.

Dead end on input

Could we have a link to the rule list in the Redirect rule updated/published. notice?

Undefined property: stdClass::$delete_posts

In wp-admin/includes/class-wp-posts-list-table.php:209

protected function get_bulk_actions() {
$post_type_obj = get_post_type_object( $this->screen->post_type );
...
209: $post_type_obj->cap->delete_posts

False negative in unit tests

the defined redirects are not cleaned between assertion, so for a similar tests it can happen that if one is failing it will actually pass the assertion because a previously defined redirect does the job instead

Full wp-cli support

Building off #31, it would be nice to have full wp-cli support with the following subcommands:

  • create
  • delete
  • list
  • clear-cache

I'll take a swing at this over the next couple of weeks

Improve check_for_possible_redirect_loops() efficiency

Currently, check_for_possible_redirect_loops() compares each redirect to every other redirect twice.

We should be able to do something like this to improve efficiency.

for ( $i = 0; $i < count( $redirects ); $i++ ) {
    for ( $j = $i + 1; $j < count( $redirects ); $j++ ) {
        // compare $redirects[$i] to $redirects[$j]
    }
}

If we're checking each redirect against itself when it is originally created, the inner loop can be $j = $i + 1, otherwise it needs to be $j = $i.

Bump version post-Composer support

I noticed that the most recent release tagged was before composer.json was added; this means that a Composer installation that requires stable won't succeed in installation (I believe).

Request a bump to include that support and other recent commits. :)

Export rules

Please can you insert a export rules created feature so i can import rules created in a new wordpress installation?
thanks

Caching Strategy Not Effective with 1000+ Redirects

I was using the plugin today on a huge site. We wanted to insert 11,000+ redirects. This resulted an exceeded memory limit fatal error.

The plugin caches all the published redirects in a transient. Then on each page request, the current page is checked against every redirect in the transient. This results in worst case performance O( n ). I think we can definitely do this better.

Permalinks and cache clearance

Some caching systems need a URL to clear a cache at their URL, for example a Varnish of Nginx based caching system. If the Safe Redirect Manager returned the "from" URL (where possible, i.e. where no regex is enabled) then this would enable some cache clearance operations.

Would you accept a pull request to implement a filter on filter_post_type_link to return the "from" URL from get_permalink.

Here's the commit in my fork to do this: simonwheatley@cba5a71

An example of this issue is the Varnish caching setup in WP Engine, where 404s are cached for a long length of time. Occasionally the solution to a 404 with a lot of incoming links is to create a redirect. Creating the redirect_rule post does not trigger a cache clearance, because WP Engine cannot get the URL to clear the cache on.

i18n support

Generate a POT file and add it to a /languages/ folder

Creating a redirect for '/' drops the "Redirect From" field

I created a redirect from "/" to "http://apple.com/" and hit publish. The "/" was dropped from the "Redirect From" field but the plugin told me the redirect was published.

Also, the title ended up as "Auto Draft" (viewable from the Manage Redirects view), and I see warnings like this:

[23-Aug-2012 18:12:50 UTC] PHP Warning: Missing argument 2 for SRM_Safe_Redirect_Manager::filter_admin_title() in /Users/danielbachhuber/wp/wp-content/plugins/safe-redirect-manager/safe-redirect-manager.php on line 132

Simple loop detection

check_for_possible_redirect_loops() is kind of slow. We could add simple loop detection that runs in constant time by checking each redirect individually when it is created. It won't be as comprehensive, but will protect against the most blatant redirect loops.

We should block:

  • any rule that redirects to itself
  • any rule that redirects all traffic to the current site

Example of the second:

/(.*) -> /$1/

Redirecting ALL traffic to the same site will always be a loop.

WordPress.com VIP feedback at commit aa09d38530

Howdy,

I took a look at your plugin this morning. It's pretty neat! I think a lot of VIPs will enjoy using it. Here's some feedback I had:

Code level feedback:

  • When we originally suggested using a custom post type, the recommendation was to store all of the redirects in one post, instead of creating a post for each redirect. Having seen your implementation, doing it the way you've done could lead to interesting features (like being able to schedule a redirect). I might remove the visibility option though, and just have a draft or published status
  • Should action_redirect_chain_alert() run on every admin request, or just in the context of the plugin? If you're doing a massive get_posts() on every admin page load, probably best to just do it in the context of the plugin
  • Similarly, you should create a WP_Query() object instead of using get_posts() so you can limit your query to just posts and postmeta (no taxonomy lookup) and benefit from the built-in caching on wpcom
  • There's some spaces that slipped into your indentation
  • It would be nice to have a filter where one could limit the number of redirects that can be created.

Aesthetic feedback:

  • I'd make this a submenu under tools, as top-level menus should generally be saved for collections of functionality
  • When creating a new redirect rule, it might be nice to use the placeholder attribute on the input fields to suggest the format the redirects should be added in.
  • I'm not sure "author" is a relevant column. You can probably remove it.
  • When I created a '/apple/' redirect to 'http://apple.com/', searching for 'Apple' produced no results. Searching your redirects by the from and to values would be pretty useful.
  • Similarly, make sure your bulk actions and quick edit are relevant… I think they could probably be removed.
  • I'd make the page title for managing all redirects "Safe Redirect Manager" and use your icon as the page icon

Hope this helps! I figured I'd give this to you all as one issue, and you can break it into separate issues as you need. None of these are blockers, but improvements we'd love to see before deploying. Let me know what you think.

Only apply redirects on 404

It would be neat to be able to enable, via a filter, the ability to only apply redirects if the current page is 404ed. This would be useful when SRM is being used to handle redirects from old post slugs to new post slugs.

Improved Documentation

I think we should have a README.md file rather than showing readme.txt. I'd like the new readme to run through configuring the plugin and adding a few redirects. This is an awesome plugin; it's a shame the documentation is so poor.

Possible Bug with URL with Accentuation

I guess I found a possible bug in the plugin.

Here there is a URL giving me 404:

https://inglesnarede.com.br/dicas-de-ingles/4-maneiras-de-chamar-alguem-de-“pao-duro”-em-ingles/

There is the (") in the url... After changing the url in the Safe Redirect Manager for a new one, the url above is not redirected. I also tried checking the regular expressions checkbox with no success.

My guess is the plugin is not checking if the url has accentuation. And if it is checking, it is not being able to redirect it.

Case insensitive URLs

I want to be able to add a redirect for /icecream and have any cased variation of it to work (/ICECREAM or /iCeCrEaM).

"Test" Quick Action

It would be nice to have a "Test" quick action for each redirect so you could actually test the redirect.

Wildcard redirects do not work

It doesn't appear that wildcard redirects are working, as I am still getting Page Not Found errors when viewing the old URL.

In the Redirect URL field I have: /gallery/before-after/*
and in the Redirect To: /gallery/ (and also /gallery/*)

However when I still try to visit the URL http://www.bellavou.co.uk/gallery/before-after?pid=2522, I'm still shown a Page not found message, and it doesn't seem as though the redirect is working at all.

I have several other redirects that do not use wildcards, and these seem to work fine.

Support for wildcard redirects

It would be great if I could easily redirect all requests to /blog/* (or any URI pattern with a wildcard) to a new URL or URI pattern.

Quick Edit and Bulk Edit

An idea for the plugin, maybe I'll create a PR in the coming days.

When you already have several redirections created but they are with the "wrong" HTTP Status Code, you have to manually to change them.

I suggest adding a quick edit and also a bulk edit to the plugin to make it easier to edit in bulk several redirections at once.

Undefined path key from parse_url

If site_url() does not have a path, it is possible that parse_url returns an array without a path key set. This causes an error when checking for its value.

Redirecting from files past root level doesn't trigger redirect

When you try to redirect from a file past the root level (for example, /files/whatever.pdf) it doesn't trigger the rewrite rule to the destination page/file.

To replicate

  • Create a new redirect rule
  • In the "from" field add something like /files/myfiles/whatever.pdf)
  • Select another url as the destination (I picked something in my uploads directory like /wp-content/uploads/2014/08/my-new-file.pdf)
  • Save the redirect rule
  • Visit the url (http://example.org/files/myfiles/whatever.pdf); observe a server-level 404 response

Custom WP_Importer

It would be nice to have a custom WP_Importer implementation (Tools > Import) for bulk-importing redirects via CSV. The import_file() method would be responsible for most of the logic, but this would allow sites with limited/no WP-CLI access to import sites without involving their hosts.

Redirect front page

This plugin doesn't seem to work to redirect the front page of a site. I tried today to redirect all of the pages on an old unused site on one domain, to similar pages on a newly updated site, and found that the front page wouldn't redirect.

Everything else redirected just fine, and I like this plugin a lot. Here's hoping I'm just missing something.

Store revisions for redirect rules

Revisions are useful to see when and who made changes to a redirection - especially if the change causes problems.

We can also limit the number of revisions using wp_revisions_to_keep if there is concern around storing too many.

No Bulk Delete

Not having the ability to bulk delete is pretty annoying when dealing with a large amount of redirects.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.