在 nginx 中从 robots.txt 重定向到 robots.php

问题描述

我使用 CentOS7 和 Nginx。我需要动态robots.txt为此我尝试使用从robots.txt重定向到robots.PHP。但如果 site.com/robots.txt 我看到来自文件 robots.PHP 的文本,如果 site.com/robots.PHP 我看到运行这个程序的结果。我如何修复 site.com/robots.txt 给我运行 robots.PHP 的结果? 在 Nginx 中,我使用下一个代码

location /robots.txt { alias /home/xxx/web/site.ru/public_html/robots.PHP; }

解决方法

虽然注释中的 rewrite 方法可行,但值得注意的是,正确的解决方案是精确匹配的位置,它无条件地将请求定向到 PHP-FPM,如下所示:

location = /robots.txt {
    fastcgi_param SCRIPT_FILENAME $document_root/robots.php;
    include fastcgi_params;
    # override SCRIPT_NAME which was set in fastcgi_params
    fastcgi_param SCRIPT_NAME /robots.php;
    fastcgi_pass unix:/var/run/php-fpm/example.com.sock;
}