请帮我理解子域robots.txt的简单nginx重写问题

时间:2011-03-31 10:41:30

标签: nginx subdomain rewrite robots.txt

对于我的子域名,我想指向不同的robots.txt文件。我曾希望以下代码能够正常工作:

if ($host ~ subdomain) {
    rewrite ^/favicon.ico$ /favicon.ico break;
    rewrite ^/robots.txt$ /robots.subdomain.txt break;
    rewrite ^/([^\/]*)?/?(.*)?$ /index.php?in1=$1&in2=$2&$query_string last;
}

favicon.ico工作正常,所有其他扩展都被重写为index.php就好了,但robots.txt也是如此。

我浪费了很多时间来尝试解决它,我在robots.txt重写之后添加了以下行。

    rewrite ^/robots.subdomain.txt$ /robots.subdomain.txt break;

有人可以帮助我,为什么它只在我添加此行时才有效,如果您发现任何明显的低效率,我的欢迎也会受到欢迎!谢谢。

1 个答案:

答案 0 :(得分:0)

这应该是你要找的东西:

location / {
  rewrite ^/robots.txt$ /robots.$host.txt; # rewrites robots.txt

  try_files $uri $uri/ @php; # try_files serves statics and sends everything else
                             # to your front controller (index.php)
                             # files such as favicon.ico get served normally
}

location @php {
 rewrite ^/([^\/]*)?/?(.*)?$ /index.php?in1=$1&in2=$2 last;
}

唯一需要注意的是,您的robots.txt需要以完整主机命名,因此在上面的示例中,您的www.domain.com需要在文档根目录中包含robots.www.domain.com.txt文件。这看起来有点难看,所以我会这样做:

rewrite ^/robots.txt$ /$host.robots.txt;

然后将文件命名为www.example.com.robots.txt