Fixing Drupal Redirect Error: How to Use TrustedRedirectResponse for External URLs

Drupal is a powerful content management system that is known for its flexibility and customizability. However, like any other software, Drupal can sometimes throw error messages that can be frustrating to deal with. One such error message that Drupal users might encounter is the "Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it" error. This error message indicates that Drupal is preventing you from redirecting to an external URL by default.

This is a security feature that is designed to protect your website and its users from potential malicious attacks. However, if you need to redirect to an external URL, you can use the \Drupal\Core\Routing\TrustedRedirectResponse class to bypass this security feature.

In this article, we will explain how to fix this error in Drupal by moving the content of web directory to the root in 5 steps.
  1. From the root directory run this command in terminal
    $ mv web/* .
    
  2. Remove web directory
    $ rmdir web
    
  3. Open autoload.php file in text editor and change the autoload file path
    return require __DIR__ . '/vendor/autoload.php';
    
  4. remove web directory from composer.json file
    "extra": {
        "drupal-scaffold": {
            "locations": {
                "web-root": "./"
            }
        },
        "installer-paths": {
            "core": [
                "type:drupal-core"
            ],
            "libraries/{$name}": [
                "type:drupal-library"
            ],
            "modules/contrib/{$name}": [
                "type:drupal-module"
            ],
            "profiles/contrib/{$name}": [
                "type:drupal-profile"
            ],
            "themes/contrib/{$name}": [
                "type:drupal-theme"
            ],
            "drush/Commands/contrib/{$name}": [
                "type:drupal-drush"
            ],
            "modules/custom/{$name}": [
                "type:drupal-custom-module"
            ],
            "profiles/custom/{$name}": [
                "type:drupal-custom-profile"
            ],
            "themes/custom/{$name}": [
                "type:drupal-custom-theme"
            ]
        },
        ...
      }
    
  5. Update drupal dependencies by running
    composer update
    
    Finally Clear cache and try again, i hope it will help you