大网数据广告活动
服务器运维问答

Setting noindex some pages on NGINX

· 52CE 我爱测

I want to set noindex some URLs. If any URL contains ?lang= | ( start with ) /plugin | ( start with ) /account it should be noindex by adding HTTP header in NGINX configuration. I tried below code before, location ~ .*/(?:?lang|p…

问题原文

原帖链接 · Serdar Koçak · CC BY-SA 4.0

I want to set noindex some URLs. If any URL contains ?lang= | (start with) /plugin | (start with) /account it should be noindex by adding HTTP header in NGINX configuration.

I tried below code before,

location ~ .*/(?:?lang|plugin|account)/.* {
    add_header X-Robots-Tag "noindex, follow" always;      
}

Other NGINX location directives that I use for my website: (These default directive for my script are working well.)

#Disable access to sensitive files
location ~* /(app|content|lib)/.*\.(po|php|lock|sql)$ {
    deny all;
}
#CORS headers
location ~* /.*\.(ttf|ttc|otf|eot|woff|woff2|font.css|css|js) {
    add_header Access-Control-Allow-Origin "*";
}
#Upload path for image content only and set 404 replacement
location ^~ /images/ {
    location ~* (jpe?g|png|gif) {
        log_not_found off;
        error_page 404 /content/images/system/default/404.gif;
    }
    return 403;
}
#Pretty URLs
location / {
    index index.php;
    try_files $uri $uri/ /index.php?$query_string;
}

Although no error messages when I reload the Nginx, the noindex directive doesn't appear.

已采纳解答

原帖链接 · Tero Kilkanen · CC BY-SA 4.0

location directives only match normalised URIs, which don't include query arguments. This is the reason why you cannot match ?lang.

To match that one, you can use a query argument variable to make the match.

if ($arg_lang) {
    add_header X-Robots-Tag "noindex, follow" always; 
}

This snippet should be included in the location / block.

For matching the other cases, I would do the following:

location /plugin {
    add_header X-Robots-Tag "noindex, follow" always; 
    try_files $uri $uri/ /index.php?$query_string;
}

location /account {
    add_header X-Robots-Tag "noindex, follow" always; 
    try_files $uri $uri/ /index.php?$query_string;
}

It is important to include the try_files statements in these, since only one location block is selected to be used.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-08-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。