Automatically add rel=nofollow to links in HTML, using PHP

1.0.0 2019-01-14 09:19 UTC

This package is auto-updated.

Last update: 2024-02-14 20:11:42 UTC


This simple PHP package has one simple purpose; to take some HTML (as a string), go through it and add rel="nofollow" to all links, subject to certain exceptions.

So give it this:

<p>Check out our <a href="">affordable web design services</a>!</p>

...and you get this:

<p>Check out our <a href="" rel="nofollow">affordable web design services</a>!</p>

By default, it will ignore relative links, so this would remain untouched:

<p>Check out the <a href="/about">about</a> page</p>

It will also ignore absolute links to the current domain.

You can also provide a whitelist of domains, and it will skip them.


composer require lukaswhite/auto-no-follow


Create an instance:

$processor = new \Lukaswhite\AutoNoFollow\Processor();

Optionally specify the current host:


If you don't set this, it'll grab it from $_SERVER['HTTP_HOST']

Then run:

$html = $processor->addLinks('<p>Check out our <a href="">affordable web design services</a>!</p>');

The method signature is this:

public function addLinks($html, $whitelist = array(), $ignoreRelative = true)

So, to whitelist certain hosts:

$html = $processor->addLinks(
  '<p>Check out our <a href="">affordable web design services</a>!</p>'

To add nofollow to relative links anyway, set the third argument to true, e.g.:

$html = $processor->addLinks(
  '<p>Check out the <a href="/about">about</a> page</p>'

This will output the following:

<p>Check out the <a href="/about" rel="nofollow">about</a> page</p>


The package contains tests, to run them: