You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单Nginx Server块中根据子域名返回不同robots.txt配置

解决方案

你可以在单个server块内实现需求,以下两种方案任选其一:

方案一:使用if指令结合alias

假设你的robots.txt和disabled-robots.txt存放在网站根目录(比如/var/www/html/),配置如下:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name v2.example.com example.com;

    root /var/www/html;

    location = /robots.txt {
        if ($host = v2.example.com) {
            alias /var/www/html/disabled-robots.txt;
        }
        # 非v2域名默认返回根目录下的robots.txt
    }

    # 其他业务location配置...
}
  • 注意alias后必须填写文件的绝对路径,且Nginx进程要有该文件的读取权限
  • 若需忽略域名大小写,可把判断改为if ($host ~* ^v2\.example\.com$)

方案二:使用map指令(推荐)

这种方式更符合Nginx最佳实践,效率更高,可读性更好:

# 在http块内添加映射规则(放在server块外部)
map $host $robots_file {
    default         robots.txt;
    v2.example.com  disabled-robots.txt;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name v2.example.com example.com;

    root /var/www/html;

    location = /robots.txt {
        try_files /$robots_file =404;
    }

    # 其他业务location配置...
}

map会在Nginx加载配置时完成映射,比运行时的if判断更高效,适合多域名场景扩展。

内容的提问来源于stack exchange,提问作者senty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:40:46