Fixing “/robots.txt” Outside Location “\.php$” in NGINX

nginx

Trying to set up cloudflare cache plugin for nginx, "/robots.txt" is outside location ".php$" is the error Im getting. Robots.txt file exist in worpress thanks in advance.

server {

server_name www.mydomain.com mydomain.com;

access_log /srv/www/mydomain.com/logs/access.log;

error_log /srv/www/mydomain.com/logs/error.log;

root /srv/www/mydomain.com/public_html;

index index.php;

location / {

try_files $uri $uri/ /index.php?$args;

}

location ~ .php$ {

include /etc/nginx/fastcgi_params;

fastcgi_pass unix:/var/run/php-fpm/www.sock;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

location ~* .(xml|xsl)$ { add_header Cache-Control "no-cache, no-store, must-revalidate, max-age=0"; expires -1; }

location /robots.txt { add_header Cache-Control "no-cache, no-store, must-revalidate, max-age=0"; expires -1; }

location /wp-cron.php { add_header Cache-Control "no-cache, no-store, must-revalidate, max-age=0"; expires -1; }

Best Answer

The Nginx configuration part you presented is syntactically incorrect (it's incomplete). Please check all your opening braces have the corresponding close braces.

The problem, as I see it, is linked to this. Your location ~ .php$ block doesn't appear to have a closing brace where I'd expect it, and the block location /robots.txt appears as a subblock of it. Which is the source of an error.

The most easy way to avoid such mistakes is to always consistently indent your configuration files. This indentation is not just for prettiness. It's for your own sake, to make less such mistakes:

location ~ .php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/var/run/php-fpm/www.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

This is the close brace your configuration appears to be not having there.