How to create a redirection programmatically? 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?
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' =&gt; 'redirects/redirect1',
    'redirect_redirect' =&gt; 'internal:/node/1',
    'language' =&gt; 'und',
    'status_code' =&gt; '301',
  ])-&gt;save();

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