When I create a node, I often need to add links to external websites in the text.

I want all the external links to open in a new tab and I want them to have a nofollow.

The body field uses CKEditor.

How do I apply nofollow and target_blank on external links in text created with CKEditor?

2 Answers 2


You can do this automatically by creating your own text filter in a custom module.

Note that the /** @Filter ... */ in front of the class is not a comment, but an annotation, it has to be included in the file. Replace all fancy uppercase stuff with your own code.



namespace Drupal\MY_MODULE\Plugin\Filter;

use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Drupal\Component\Utility\Html;

 * @Filter(
 *   id = "MY_FANCY_FILTER",
 *   title = @Translation("My fancy filter"),
 *   description = @Translation("Makes HTML even more fancier"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
 * )
class MYFANCYFILTER extends FilterBase {

  public function process($text, $langcode) {
    $result = new FilterProcessResult($text);
    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);

    // to select all links you have to create a XPath query 
    // the example query below selects all <a> tags which have a "href" attribute
    // see https://www.w3schools.com/xml/xpath_syntax.asp
    foreach ($xpath->query("//a[@href]") as $element) {
      // the example logic below accepts all links starting with "http://" or "https://" or "//"
      if (preg_match('|^(https?:)?//.+|', $element->getAttribute('href')) === 1) {
        // see https://www.php.net/manual/de/class.domelement.php
        // for docs about manipulating HTML markup
        $element->setAttribute('MY_ATTRIBUTE', 'MY_VALUE');
    return $result;

Then enable your new text filter for the corresponding text format in
Configuration > Content authoring > Text formats and editors


I have tried to add target="_blank" by using Text Format=Full HTML using Source button.

It worked for me.

enter image description here

If you do not want manually then you can try following module https://www.drupal.org/project/editor_advanced_link

enter image description here

  • Thanks, but I know how to do this manually, it's a lot of work for a site that posts regularly. I want to add this automatically on the external leins.
    – zoulou66
    Commented Jan 12, 2022 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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