I'm currently migrating a site to Drupal. The old site has thousands of dynamic URLs for which I cannot use a regular expression to handle them. Those URLs exist in a slightly different form in the Drupal site.
Unfortunately the URL structure is too complicated for being processed directly in a .htaccess file.
I want all the old URLs to return a 301 redirect to the new URL.
This is what I tried.
- I implemented
hook_page_preprocess()
and sent aRedirectResponse
to the new URL when the incoming URL matches the regular expression for the old URLs - I implemented an event subscriber that does basically the same on the onRequest event
In both the cases, the redirect response is sent with the following code.
$respond = new TrustedRedirectResponse($url,301);
$respond->send();
die();
Both solutions do work when the user is logged-in. In my local developing site, it works also when the user is not logged-in. On the live server, it doesn't work for anonymous users.
The funny thing is that, even when the redirection works for logged-in users, the log shows a Page not found entry for that URL. So it seems that even with the event subscriber solution, Drupal handles the 404 part first, and then executes my code.
What am I doing wrong?
Should I implement this differently?
die()
or send responses like that yourself. The event you have has a method to set a response object: Use that; see how the redirect.module does it, for example.