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' =&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.