14

I try to create a redirection 301 with the redirect module. For example, I want to redirect an URL source to an internal URL through my custom module.

I want to create a redirection when I create a node. Import old content, create a new node and keep the old path.

Anyone have an idea?

  • 1
    You should definitely add more information to your question. What have you tried so far? What is your exact problem? Why don't you mention the migration you mentioned in a comment to one of the answers? – leymannx Feb 8 '17 at 23:10
  • You can use below code snippets to create programmatically URL redirect. // Create an object with the redirect parameters $redirect = new stdClass(); redirect_object_prepare($redirect); $redirect->source = 'old-url'; $redirect->source_options = array(); $redirect->redirect = 'node/5'; // New system path $redirect->redirect_options = array(); $redirect->type = 'redirect'; $redirect->language = LANGUAGE_NONE; redirect_save($redirect); – Aryashree Pritikrishna Aug 1 '19 at 15:58
25

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 you could put code in entity hooks which updates the redirects when creating, editing or deleting a node.

|improve this answer|||||
6

You can use RedirectResponse to achieve this.

Refer the following link

https://drupal.stackexchange.com/a/138852

|improve this answer|||||
  • Thanks for your answer. But i want to create a redirection when i create a node. I import a old content in create a new node and i keep old path. – Romest Feb 8 '17 at 15:03
4

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')); 
|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.