开发者

Please help me understand simple nginx rewrite issue for subdomain robots.txt

For my subdomain I wanted to point to a different robots.txt file. I had hoped the following code would work:

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

favicon.ico works fine, all other extensions are rewritten to index.php just fine, but so is robots.txt.

I spent [wasted] a lot of time trying to solve it, which I did by adding the following line after the robots.txt rewrite.

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

Can someone please help me why it only works when I add this line, also any improvements to my config would be welcomed if you see any obvious inefficiencies! Thank you.


This should be what you're looking for:

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;
}

The only caveat is that your robots.txt needs to be named after the full host, so in the example above your www.domain.com needs to have a robots.www.domain.com.txt file in the document root. This seems a bit ugly, so I'd do it this way instead:

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

and then you name your file www.example.com.robots.txt

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜