Nginx 위치에서 add_header가 작동하지 않습니다.

Nginx 위치에서 add_header가 작동하지 않습니다.

그래서 지난 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";
}

(이것은 예로서 3개에 불과하지만 실제로는 http 블록에 포함된 파일 내에 이들 중 ~200개를 생성했습니다.)

그리고 서버 블록에 다음을 추가했습니다.

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는 제가 필요로 하는 너무 많은 변수에 충분하지 않기 때문입니다. 그럼 다른분께도 도움이 되었으면 좋겠습니다...

관련 정보