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?

  • The Redirect module contains this functionality. Unless you have another use case but then I would need more information in order to help. Commented Feb 8, 2017 at 14:25
  • You can use RedirectResponse to achieve this. Refer the following link https://drupal.stackexchange.com/a/138852 Commented Feb 8, 2017 at 14:58
  • 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
    Commented Feb 8, 2017 at 15:03
  • 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
    Commented Feb 8, 2017 at 23:10
  • 1
    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); Commented Aug 1, 2019 at 15:58

2 Answers 2


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_source' => 'redirects/redirect1',
    'redirect_redirect' => 'internal:/node/1',
    'language' => 'und',
    'status_code' => '301',

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')); 

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