Меню Закрыть

Nginx more set headers

ngx_headers_more — Set and clear input and output headers. more than "add"!

This module is not distributed with the Nginx source. See the installation instructions.

Table of Contents

This document describes headers-more-nginx-module v0.33 released on 3 November 2017.

This module allows you to add, set, or clear any output or input header that you specify.

This is an enhanced version of the standard headers module because it provides more utilities like resetting or clearing "builtin headers" like Content-Type , Content-Length , and Server .

It also allows you to specify an optional HTTP status code criteria using the -s option and an optional content type criteria using the -t option while modifying the output headers with the more_set_headers and more_clear_headers directives. For example,

You can also specify multiple MIME types to filter out in a single -t option. For example,

Never use other paramemters like charset=utf-8 in the -t option values; they will not work as you would expect.

Input headers can be modified as well. For example

The option -t is also available in the more_set_input_headers and more_clear_input_headers directives (for request header filtering) while the -s option is not allowed.

Unlike the standard headers module, this module’s directives will by default apply to all the status codes, including 4xx and 5xx .

syntax: more_set_headers [-t ]. [-s ]. .

default: no

context: http, server, location, location if

phase: output-header-filter

Replaces (if any) or adds (if not any) the specified output headers when the response status code matches the codes specified by the -s option AND the response content type matches the types specified by the -t option.

If either -s or -t is not specified or has an empty list value, then no match is required. Therefore, the following directive set the Server output header to the custom value for any status code and any content type:

Existing response headers with the same name are always overridden. If you want to add headers incrementally, use the standard add_header directive instead.

A single directive can set/add multiple output headers. For example

Multiple occurrences of the options are allowed in a single directive. Their values will be merged together. For instance

is equivalent to

The new header should be the one of the forms:

The last two effectively clear the value of the header Name .

Nginx variables are allowed in header values. For example:

But variables won’t work in header keys due to performance considerations.

Multiple set/clear header directives are allowed in a single location, and they’re executed sequentially.

Directives inherited from an upper level scope (say, http block or server blocks) are executed before the directives in the location block.

Note that although more_set_headers is allowed in location if blocks, it is not allowed in the server if blocks, as in

Behind the scene, use of this directive and its friend more_clear_headers will (lazily) register an ouput header filter that modifies r->headers_out the way you specify.

syntax: more_clear_headers [-t ]. [-s ]. .

default: no

context: http, server, location, location if

phase: output-header-filter

Clears the specified output headers.

Читайте также:  Учетная запись самсунг смарт тв забыл пароль

is exactly equivalent to

See more_set_headers for more details.

The wildcard character, * , can also be used at the end of the header name to specify a pattern. For example, the following directive effectively clears any output headers starting by " X-Hidden- ":

The * wildcard support was first introduced in v0.09.

syntax: more_set_input_headers [-r] [-t ]. .

default: no

context: http, server, location, location if

phase: rewrite tail

Very much like more_set_headers except that it operates on input headers (or request headers) and it only supports the -t option.

Note that using the -t option in this directive means filtering by the Content-Type request header, rather than the response header.

Behind the scene, use of this directive and its friend more_clear_input_headers will (lazily) register a rewrite phase handler that modifies r->headers_in the way you specify. Note that it always run at the end of the rewrite phase so that it runs after the standard rewrite module and works in subrequests as well.

If the -r option is specified, then the headers will be replaced to the new values only if they already exist.

syntax: more_clear_input_headers [-t ]. .

default: no

context: http, server, location, location if

phase: rewrite tail

Clears the specified input headers.

is exactly equivalent to

To remove request headers "Foo" and "Baz" for all incoming requests regardless of the content type, we can write

The wildcard character, * , can also be used at the end of the header name to specify a pattern. For example, the following directive effectively clears any input headers starting by " X-Hidden- ":

  • Unlike the standard headers module, this module does not automatically take care of the constraint among the Expires , Cache-Control , and Last-Modified headers. You have to get them right yourself or use the headers module together with this module.
  • You cannot remove the Connection response header using this module because the Connection response header is generated by the standard ngx_http_header_filter_module in the Nginx core, whose output header filter runs always after the filter of this module. The only way to actually remove the Connection header is to patch the Nginx core, that is, editing the C function ngx_http_header_filter in the src/http/ngx_http_header_filter_module.c file.

Grab the nginx source code from nginx.org, for example, the version 1.13.6 (see nginx compatibility), and then build the source with this module:

Download the latest version of the release tarball of this module from headers-more-nginx-module file list.

Starting from NGINX 1.9.11, you can also compile this module as a dynamic module, by using the —add-dynamic-module=PATH option instead of —add-module=PATH on the ./configure command line above. And then you can explicitly load the module in your nginx.conf via the load_module directive, for example,

Also, this module is included and enabled by default in the OpenResty bundle.

The following versions of Nginx should work with this module:

  • 1.16.x
  • 1.15.x (last tested: 1.15.8)
  • 1.14.x
  • 1.13.x (last tested: 1.13.6)
  • 1.12.x
  • 1.11.x (last tested: 1.11.2)
  • 1.10.x
  • 1.9.x (last tested: 1.9.15)
  • 1.8.x
  • 1.7.x (last tested: 1.7.10)
  • 1.6.x (last tested: 1.6.2)
  • 1.5.x (last tested: 1.5.8)
  • 1.4.x (last tested: 1.4.4)
  • 1.3.x (last tested: 1.3.7)
  • 1.2.x (last tested: 1.2.9)
  • 1.1.x (last tested: 1.1.5)
  • 1.0.x (last tested: 1.0.11)
  • 0.9.x (last tested: 0.9.4)
  • 0.8.x (last tested: 0.8.54)
  • 0.7.x >= 0.7.44 (last tested: 0.7.68)
Читайте также:  Code 0 description failed to load resource

Earlier versions of Nginx like 0.6.x and 0.5.x will not work.

If you find that any particular version of Nginx above 0.7.44 does not work with this module, please consider reporting a bug.

English Mailing List

The openresty-en mailing list is for English speakers.

Chinese Mailing List

The openresty mailing list is for Chinese speakers.

Bugs and Patches

Please submit bug reports, wishlists, or patches by

The changes of every release of this module can be obtained from the OpenResty bundle’s change logs:

This module comes with a Perl-driven test suite. The test cases are declarative too. Thanks to the Test::Nginx module in the Perl world.

To run it on your side:

To run the test suite with valgrind’s memcheck, use the following commands:

You need to terminate any Nginx processes before running the test suite if you have changed the Nginx server binary.

Because a single nginx server (by default, localhost:1984 ) is used across all the test scripts ( .t files), it’s meaningless to run the test suite in parallel by specifying -jN when invoking the prove utility.

Some parts of the test suite requires modules proxy, rewrite, and echo to be enabled as well when building Nginx.

  • Support variables in new headers’ keys.

You’ll be very welcomed to submit patches to the author or just ask for a commit bit to the source repository on GitHub.

  • Yichun "agentzh" Zhang (章亦春) , OpenResty Inc.
  • Bernd Dorn ( http://www.lovelysystems.com/ )

This wiki page is also maintained by the author himself, and everybody is encouraged to improve this page as well.

The code base is borrowed directly from the standard headers module in Nginx 0.8.24. This part of code is copyrighted by Igor Sysoev.

Copyright (c) 2009-2017, Yichun "agentzh" Zhang (章亦春) [email protected], OpenResty Inc.

Copyright (c) 2010-2013, Bernd Dorn.

This module is licensed under the terms of the BSD license.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Читайте также:  Можно ли петь караоке на ноутбуке

Ubuntu 16 Server — load_module modules/ngx_http_headers_more_filter_module.so does not work out the box from a fresh install.

While trying to install nginx-extras I receive a dependency error.

To meet the dependency, it takes me back to nginx 1.10

I installed nginx by adding to the /etc/apt/sources.list file

Can someone shed some light on my issue?

2 Answers 2

This is what I did to have enable more_set_headers on Ubuntu 16.04

I edited /etc/nginx/nginx.conf and added as my first line
load_module modules/ngx_http_headers_more_filter_module.so;

I then added in the http block
more_set_headers Server: Uber;

I checked to see if my config was okay with nginx -t
I restarted the server with service nginx restart

Большинство (если не все) веб-серверы при ответе на HTTP-запрос по умолчанию заявляют о себе с помощью заголовка Server, сообщая в лучшем случае название используемого ПО, а в хучшем – версию, используемые модули и т.д. Их можно удобно просматривать с помощью таких дополнений, как например Server Spy для Mozilla Firefox.

Но далеко не все из веб-серверов позволяют в явном виде одной директивой отключить такое поведение. На мой взгляд, это потенциальная прореха в безопасности. В данной статье показано, как отключить отсылку заголовка Server или подменить его значение на произвольное для серверов Lighttpd, Nginx, Apache, G-WAN.
Подробнее под катом.

Lighttpd

Lighttpd – единственный из перечисленных серверов, в файле конфигурации которого предусмотрена подмена заголовка Server. Выглядит это так:
server.tag = "gws"

Nginx

Не раз встречал в Сети инструкции, как изменить заголовок Server в веб-сервере Nginx. Делается все в лоб – с помощью подмены значения в исходниках и перекомпиляции. Например www.xakep.ru/post/54168
Есть метод более простой. Достигнуть результата можно использованием комбинации модулей HttpHeadersModule и HttpHeadersMoreModule или еще более простой вариант с помощью одного HttpHeadersMoreModule.

С использованием комбинации модулей HttpHeadersModule и HttpHeadersMoreModule:
# Удаляем существующее значение заголовка Server
more_clear_headers ‘Server’;
# Задаем новое
add_header Server gws;

С помощью одного HttpHeadersMoreModule:
# только HttpHeadersMoreModule
more_set_headers ‘Server: my-server’;

Apache

В веб сервере Apache содержимое заголовка Server настраивается с помощью ServerTokens
По умолчанию используется значение Full. Показывается информация вида Apache/2.4.1 (Unix) PHP/4.2.2 MyMod/1.2
Минимум, к которому можно свести – это Apache. С помощью mod_header пробовал сделать конфигурацию, аналогичную Nginx. Не получилось – Apache игнорирует настройки и продолжает упорно выставлять значение Server согласно ServerTokens и ServerSignature.
Пришлось поставить mod_security и добавить в конфигурацию строку:
SecServerSignature "gws"
Заработало.

В случае с G-WAN конфига как такового не существует. Код на C в handler’е выглядит следующим образом:

xbuf_xcat(get_reply(argv),
"HTTP/1.1 200 OK
"
"Content-type: text/html
"
"Content-Length: 20
"
"Server: gws
"
"Connection: keep-alive

"
"Hello, World");

// set the HTTP reply code
int *pHTTP_status = (int*)get_env(argv, HTTP_CODE);
if(pHTTP_status)
*pHTTP_status = 200; // 200:OK
return 2;

Тонкости настройки G-WAN не являются темой данной статьи, поэтому в детали не вдаюсь.

Рекомендуем к прочтению

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

*

code

Adblock
detector