add_header 在 Nginx 位置不起作用

add_header 在 Nginx 位置不起作用

所以,在過去的 8 個小時裡我一直在試圖解決這個問題,但似乎我被困住了...

我有以下 Nginx 設定檔:

server_tokens off;

upstream php-handler {
  server unix:/var/run/php5-fpm.sock;
}

server {
  listen 80;
  server_name     domain.net;
  access_log      /var/log/nginx/domain.net-access.log;
  error_log       /var/log/nginx/domain.net-error.log;




  location ~* \.(jpg|jpeg|gif|png|js|css|ico|eot|woff|ttf|svg|cur|htc|xml|html|tgz)$ {
       expires 24h;
  }

  root /var/www/html/domain.net;

  index index.php;


  location ~ ^/cars/sale(.*) {
        add_header X-Robots-Tag "noindex, nofollow" always;
        try_files $uri $uri/ /index.php;
  }

  location ~ ^/(?:\.htaccess|config){
       deny all;
  }

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


 location ~ \.php(?:$|/) {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_pass php-handler;
    fastcgi_read_timeout 120s;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_ignore_client_abort on;
    fastcgi_param  SERVER_NAME $http_host;
  }

}

問題是,無論我嘗試什麼,都沒有添加“/cars/sale”位置的 X-Robots-Tag。我猜測這是因為請求被傳遞到最終的“.php”位置,其中先前添加的標頭被遺忘。有什麼方法可以讓我只為該特定位置添加此標頭而不使用 more_set_headers ?

答案1

你實際上可以這樣做:

map $request_uri $robot_header {
    default "";
    ~^/cars/sale(.*) "noindex, nofollow";
    ~^/bikes/sale(.*) "noindex, nofollow";
    ~^/motorbikes/sale(.*) "noindex, nofollow";
}

但如果它們都遵循這種模式,那麼你可以這樣做:

map $request_uri $robot_header {
    default "";
    ~^/(.+?)/sale(.*) "noindex, nofollow";
}

你的配置相當混亂。使用正規表示式時,Nginx 將選擇第一個符合的區塊來滿足您的請求,因此列出它們的順序很重要。

您可以在汽車位置區塊中嵌套另一個 php 區塊,並在其中新增標頭。如果您將 php 處理程序指定為上游伺服器,那麼您不必每次都包含所有 fastcgi 參數,這會使事情變得更加整潔。

答案2

所以……我在睡了一夜之後想到了一個解決辦法。這是一個非常骯髒的修復,但它實際上是我的特定情況下唯一有效的方法:

在 http 區塊中我新增:

map $request_uri $robot_header1 {
    default "";
    ~^/cars/sale(.*) "noindex, nofollow";
}

map $request_uri $robot_header2 {
    default "";
    ~^/bikes/sale(.*) "noindex, nofollow";
}

map $request_uri $robot_header3 {
    default "";
    ~^/motorbikes/sale(.*) "noindex, nofollow";
}

(這只是三個例子,但我實際上已經在一個文件中生成了大約 200 個,並將其包含在 http 區塊中)

在伺服器區塊中我新增了:

add_header X-Robots-Tag $robot_header1;
add_header X-Robots-Tag $robot_header2;
add_header X-Robots-Tag $robot_header3;
...

我還必須將 Nginx 參數“variables_hash_bucket_size”增加到 512,因為預設值 64 不足以滿足我需要的這麼多變數。所以,我希望這對其他人也有幫助......

相關內容