Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

justl00king's avatar

Having trouble adding headers to specific path in NGINX

Trying to add a no index header to a specific path (/path) but it doesn't show up. When I add it in with the other add_header lines, it shows just fine but not when put into location /path {} or even location / {}.

Here's my nginx file:

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;

server_name mydomain.com;
root /home/forge/mydomain.com/public;

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "origin";
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";

index index.html index.htm index.php;

charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location /path {
    add_header X-Robots-Tag "noindex" always;
    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

error_page 404 /index.php;

location ~ \.php$ {

    try_files $uri /index.php =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

location ~ /\.(?!well-known).* {
    deny all;
}
}
0 likes
3 replies
justl00king's avatar

Thanks, @bobbybouwmann, appreciate your help on this. You're right, the try_files in location / & /path passes processing on to the PHP location block, which means no headers are added. What I ended up doing that worked instead of including an external file was added the add_header X-Robots-Tag to the server block with the others and then used a map to control its value based on the $request_uri. Hope that helps someone else that might come across this.

Please or to participate in this conversation.