I am running PHP in Apache2 server. I would like to add header("X-Robots-Tag: noindex", true);
to my pages if the url contains any get parameters like https://example.com/?
or https://example.com/a.php?
or https://example.com/a.php?key=value
. So basically, if the url contain ?
charter, the header needs to be added.
Is it possible to do it using .htaccess
file and how to do it? Or is there any other way to achieve this?
like
https://example.com/?
orhttps://example.com/a.php?
The issue in these two instances are that the query string is empty , so you can't check for this using the standard QUERY_STRING
server variable ("empty" and "not-exists" evaluate to the same thing, ie. empty ).
However, you can check for a literal ?
(ie. query string delimiter) in the first line of the HTTP request headers, as contained in the THE_REQUEST
Apache server variable.
In the case of the first example above, this will contain a string of the form:
GET /? HTTP/1.1
And for /a.php?key=value
, this will be:
GET /a.php?key=value HTTP/1.1
We can use mod_rewrite to check this and set an environment variable. Then use the header
directive to set the required X-Robots-Tag
HTTP response header conditionally based on whether this env var is set.
For example, near the top of the root .htaccess
file:
RewriteEngine On
# Check for literal "?" in URL and set QUERY_EXISTS env var
RewriteCond %{THE_REQUEST} \s/.*\?
RewriteRule ^ - [E=QUERY_EXISTS:1]
# Set header if QUERY_EXISTS is set
header set X-Robots-Tag "noindex" env=QUERY_EXISTS
This sets the header on 2xx "OK" responses. It won't, for instance, set the header on a 404 - but 404s are not indexed anyway, so the header is redundant. However, if you specifically need to set the header on all (non-2xx) responses then use the always
condition. For example:
# Use "always" to set on non-2xx responses as well
header always set ....
Note that this is also dependent on other directives you might have in your .htaccess
file. For example, if you have existing mod_rewrite directives that cause the rewrite engine to "loop" then the env var will be renamed to REDIRECT_QUERY_EXISTS
and you will likely need to check for this instead in the header
directive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.