HTACCESS – How to Add X-Robots-Tag to a Specific Directory

.htaccess

I've tried to look for this answer here as well as Stackoverflow and could not find an applicable answer.

I'm trying to add X-Robots-Tag 'noindex' to a specific directory on my website via HTACCESS.

Purpose: I want to prevent all pages within this directory from being indexed by search engines.

My Setup: PHP version 5.6.40 / Apache / Linux

Clarification: This is not a physical directory. This is a virtual directory that exists via URL rewrite.

Example URL: http://www.example.com/newsletters/

Example URL: http://www.example.com/newsletters/spring.html

Best Answer

Create a .htaccess file in that directory with the following mod_headers directive:

Header set X-Robots-Tag "noindex"

UPDATE#1: If this was a 'virtual' directory, how would the approach differ?

In that case, use the .htaccess file in the document root and set an environment variable (eg. NOINDEX) when the required URL-path is requested and set the X-Robots-Tag conditionally based on whether the env var is set.

For example:

SetEnvIf Request_URI ^/virtualdirectory/ NOINDEX
Header set X-Robots-Tag "noindex" ENV=NOINDEX

SetEnvIf is part of mod_setenvif.

The ENV= argument to the Header directive allows you to set that header only if the stated env var is set.

UPDATE#2: Apache 2 I believe.

If you are on Apache 2.4+ (as opposed to Apache 2.2) then you can use an Apache expression instead of having to set an environment variable. For example:

<If "%{REQUEST_URI} =~ m#^/virtualdirectory/#">
Header set X-Robots-Tag "noindex"
</If>
Related Topic