Drupal - How to create a redirection programmatically?

If you want to store redirects in database use the module Redirect. This module provides a user interface to add redirects. The redirects are stored in a content entity, which you can also create programmatically:

use Drupal\redirect\Entity\Redirect;

  Redirect::create([
    'redirect_source' => 'redirects/redirect1',
    'redirect_redirect' => 'internal:/node/1',
    'language' => 'und',
    'status_code' => '301',
  ])->save();

You can do this at the time you create nodes from imported data or in entity hooks when inserting, updating or deleting nodes.


You can change your .htaccess by adding this code :

#custom redirects
RewriteRule ^old/URL/path$ http://example.com/new/path [R=301,L]
#end custom redirects

Or if you want do this in Drupal :

return new RedirectResponse(Drupal\Core\Url::fromUri('route_name')); 

Tags:

8

Redirection