Apache httpd
Additional Modules
Rozšiřující moduly

Lukáš Bařinka

© 2021

REV 2.10

Module types overview

Přehled typů modulů

  • System environment
  • Authentication and access control
  • Dynamic content generating
  • Mime-type configuration
  • Directory listing
  • Response headers
  • Server information and logging
  • URL mapping and rewriting
  • Systémové prostředí
  • Autentizace a řízení přístupu
  • Dynamické generování obsahu
  • Konfigurace typu obsahu
  • Adresářové výpisy
  • Hlavičky odpovědí
  • Informace o serveru a logování
  • Mapování URL

TOC

Obsah

  1. Modules configuration
  2. Multi-Processing Modules (MPM)
  3. Server information and logging
  4. LAB: Logging
  5. MIME information
  6. Content negotiation
  7. LAB: Content negotiation
  1. Práce s moduly
  2. Moduly pro souběžné zpracování (MPM)
  3. Moduly pro logování a informace o serveru
  4. LAB: Logování
  5. Modul pro práci s MIME informacemi
  6. Dojednávání obsahu
  7. LAB: Dojednávání obsahu

Modules configuration

Práce s moduly

Dynamic loading module (mod_so)

Dynamické načítání modulů (mod_so)

  • LoadModule identifier module_pathname
  • Identifier is defined inside every module (entry point)
  • Pathname is relative to ServerRoot, suffix is .so by default
  • Context: server <IfModule …> container follows usualy
  • LoadModule identifikátor cesta_k_modulu
  • Identifikátor je definovaný uvnitř každého modulu
  • Cesta je relativně k ServerRoot, název modulu obvykle s příponou .so
  • Kontext: server, obvykle následuje použití kontejneru <IfModule …>

Dynamic loading example

Příklad dynamicky načítaného modulu


								LoadModule alias_module modules/mod_alias.so

								<IfModule alias_module>

								  Alias /vhosts /var/www/vhosts

								  <Directory /var/www/vhosts>
								    DefaultType text/html
								    AddDefaultCharset utf-8
								    Require all granted
								  </Directory>

								</IfModule>
							

Another module setup

Další činnosti s moduly

  • Configuration check (test) It is important to use as same definitions as in server start (-D def) Kontrola (testování) konfigurace Je nutné uvést používané definice (-D def)
    
    									apachectl -t -D SSL -D PHP5 -D USERDIR -D INFO
    									[time] [warn] The Alias directive in .../00_mod_autoindex.conf at line 5 will probably never
    									match because it overlaps an earlier Alias.
    								
  • Loaded modules into server Take only configuration files into account, not the running server Zjištění modulů načítaných do serveru Bere v úvahu pouze konfigurační soubory, nikoliv běžící server
    
    									apachectl -M
    									Loaded Modules:
    									  core_module (static)
    									  mpm_worker_module (static)
    									  …
    									  alias_module (shared)
    									  auth_basic_module (shared)
    									  …
    								
  • List of compiled static modules List staticky zkompilovaných modulů
    
    									apachectl -l
    									Compiled in modules:
    									  core.c
    									  worker.c
    									  http_core.c
    									  mod_so.c
    								

Modules for concurrent request processing (MPM)

Moduly pro souběžné zpracování (MPM)

Multi-processing modules

  • Child (processes and threads) creation to serve concurrent requests on listening ports
  • Choice of MPM during compilation configuration --with-mpm=name
  • MPM usage is exclusive and typically based on underlying OS
    • UNIX prefork – processes (contemporary) worker – threads (old) event – threads (contemporary)
    • Windows mpm_winnt
    • BeOS beos
    • Netware mpm_netware
    • OS/2 mpmt_os2
  • Kontrola vytváření potomků (procesů a vlákan) k obsluze požadavků na určených portech
  • Volba MPM při konfiguraci kompilace --with-mpm=jméno
  • Použití MPM je výlučné a obvykle záleží na použitém OS
    • UNIX prefork – procesy (aktuální) worker – vlákna (starší) event – vlákna (aktuální)
    • Windows mpm_winnt
    • BeOS beos
    • Netware mpm_netware
    • OS/2 mpmt_os2

MPM - prefork

Requests served by processes

Obsluhu požadavků zajišťují procesy

Prefork MPM scheme

MPM - worker

Requests served by threads inside processes

Obsluhu požadavků zajišťují vlákna procesů

Worker MPM scheme

Slow-Loris Problem

Problém Slow-Loris

Slowloris
  • mod_reqtimeout type=timeout-maxtimeout,MinRate=data_rate
    
    									RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
    								
  • Sets limit for
    • headers to 20s and for each additional 500b will increase it by 1s, with hard limit set to 40s
    • body to 20s and for each additional 500b will increase it by 1s
    • 0 = no limit
  • In case of limit overrun is server response: 408 REQUEST TIME OUT
  • mod_reqtimeout type=timeout-maxtimeout,MinRate=data_rate
    
    									RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
    								
  • Nastavuje limit pro
    • hlavičky na 20s a za každých 500b jej navíší o 1s, maximálně však na 40s
    • tělo na 20s a za každých 500b jej navýší o 1s
    • 0 = bez limitu
  • Při nedodržení limitu server vrací: 408 REQUEST TIME OUT

MPM - event

Requests served by threads inside processes, dedicated thread to handle connections

Obsluhu požadavků zajišťují vlákna procesů, dedikované vlánkno pro obsluhu spojení

Event MPM scheme

Server information and logging modules

Moduly pro logování a informace o serveru

Modules overview

Přehled modulů

  • mod_status Provides information on server activity and performance Provides information about running environment
  • mod_info Provides a comprehensive overview of the server configuration
  • mod_log_config Provides ability to requests logging customization Allows to configure custom formats and log storage
  • mod_logio Adds logging of input and output bytes per request
  • mod_status Umožňuje kontrolovat výkon serveru Poskytuje informace o jeho běhu
  • mod_info Poskytuje informace o nastavení serveru
  • mod_log_config Poskytuje prostředky pro logování požadavků Umožňuje nastavení různých formátů logů a jejich úložišť
  • mod_logio Přidává možnost logovat množství příchozích a odchozích dat

Status module

  • The number of workers (processes/threads)
    • Working
    • Idle
  • The status of each worker
    • Number of requests
    • Total number of bytes served
  • A total number of accesses and byte count served
  • The time the server was started/restarted and the time it has been running for, CPU usage
  • The current hosts and requests being processed
  • Počet worker procesů/vláken
    • Working
    • Idle
  • Stav a statistika každého procesu/vlákna
    • Počet požadavků
    • Počet bytů
  • Celkový počet požadavků a přenesených dat a průměrné hodnoty
  • Doba běhu serveru, vytížení CPU
  • Aktuálně obsluhované požadavky

Status module configuration

Konfigurace status modulu


							<Location /server-status>

							  SetHandler server-status

							  <RequireAny>
							    Require host .admin.company.com
							    Require local
							  </RequireAny>

							</Location>
						

Status module details

Podrobnosti status modulu

  • Directives
    • ExtendedStatus Off|On Keep track of extended status information for each request
    • SeeRequestTail Off|On Displays first/last 63 characters of request line
  • URL
    • /server-status
    • /server-status?refresh=N Refresh the page every N seconds
    • /server-status?auto Machine-readable output
  • Direktivy
    • ExtendedStatus Off|On Umožňuje logovat jednotlivé požadavky
    • SeeRequestTail Off|On Ovládá záznam prvních/posledních 63 znaků z požadavku
  • URL
    • /server-status
    • /server-status?refresh=N Automatická obnova po N sekundách
    • /server-status?auto Strojově zpracovatelný výstup

Info module

  • Output contains
    • List of enabled modules
    • Available configuration directives for every used module
    • Used configuration directives for every used module
  • This module can leak sensitive information, it is recommended to limit access to that information!
    
    									<Location /server-info>
    									  SetHandler server-info
    									  Require local
    									</Location>
    								
  • Výpis obsahuje
    • Seznam použitých modulů
    • Výpis možných direktiv každého použitého modulu
    • Výpis použitých direktiv každého použitého modulu
  • Poskytované informace mohou být citlivé, je vhodné k nim omezit přístup
    
    									<Location /server-info>
    									  SetHandler server-info
    									  Require local
    									</Location>
    								

URL

  • /server-info Full information
  • /server-info?module_name Only information relevant to the named moduleE.g. mod_alias.c
  • /server-info?config Just the configuration directives, not sorted by module,
    without comments and whitespaces
  • /server-info?list Only a simple list of enabled modules
  • /server-info?server Only the basic server information
  • /server-info Komplexní informace
  • /server-info?název_modulu Informace o zvoleném modulu (např. mod_alias.c)
  • /server-info?config Konfigurace bez komentářů a bílých znaků
  • /server-info?list Seznam použitých modulů
  • /server-info?server Základní informace o serveru

Error log

Log chyb

  • Basic logging by web server (core)
  • ErrorLog file-path|syslog[:[facility][:tag]]
    • file-path logging into file
    • |file-path logging into command
    • syslog[:facility] using (UNIX) logging daemon
    • syslogd
    • syslog-ng
  • The format is customizable – ErrorLogFormat
    
    									ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [client %a] %M"
    								
  • Log contains also debug output from CGI scripts (stderr)
  • Základní logování zajišťuje jádro serveru (core)
  • ErrorLog file-path|syslog[:[facility][:tag]]
    • file-path logování do souboru
    • |file-path logování do příkazu
    • syslog[:facility] využít logovacího démona (UNIX)
    • syslogd
    • syslog-ng
  • Formát záznamu lze změnit – ErrorLogFormat
    
    									ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [client %a] %M"
    								
  • Obsahuje i ladící výstup z CGI skriptů (stderr)

Access log

Log požadavků

  • Records all requests to web server
  • Format and storage can be customized
    
    									LogFormat "%h %l %u %t \"%r\" %>s %b" common
    									CustomLog logs/access_log common
    								
    
    									147.32.80.98 - - [15/Jul/2011:14:45:49 +0200] "GET /y36aws-0 3/total.png HTTP/1.1" 200 10099
    									127.0.0.1 - - [15/Jul/2011:14:46:01 +0200] "GET /server-stat us?auto HTTP/1.0" 200 1201
    								
  • Modifiers < / > specifie origin/final request
    • In case of redirections
    • Directives %s, %U, %T, %D, and %r look at the original request, all others look at the final request
  • Záznam všech požadavků na server
  • Formát a úložiště logu lze konfigurovat
    
    									LogFormat "%h %l %u %t \"%r\" %>s %b" common
    									CustomLog logs/access_log common
    								
    
    									147.32.80.98 - - [15/Jul/2011:14:45:49 +0200] "GET /y36aws-0 3/total.png HTTP/1.1" 200 10099
    									127.0.0.1 - - [15/Jul/2011:14:46:01 +0200] "GET /server-stat us?auto HTTP/1.0" 200 1201
    								
  • Modifikátor < / > určuje první/poslední požadavek
    • V případě interních přesměrování
    • Direktivy %s, %U, %T, %D, and %r používají původní požadavek, ostatní konečný požadavek

Formatting strings examples

Příklady formátovacích řetězců

%hRemote host
%rFirst line of request
%uRemote user if the request was authenticated (! HTTP 401)
%lRemote logname (connecting process owner) From identd/authd/pidnetd/…, if supplied, else
%bSize of response in bytes, excluding HTTP headers, 0 → -
%BSize of response in bytes, excluding HTTP headers
%tTime the request was received Standard format, %{format}t according to strftime(3)
%sHTTP response status
%I
%O
Actual number of bytes sent over the network (in/out), headers included, requires mod_logio
%hremote host
%rprvní řádek z požadavku
%uremote user - z autentizace (! stavový kód HTTP 401)
%lremote logname (vlastník procesu, který inicioval spojení) Vyžaduje modul mod_ident a na vzdáleném počítači běžící démon (authd, pidentd atp.), jinak bude místo hodnoty
%bvelikost odpovědi bez http hlavičky v bytech, místo 0 je
%Bvelikost odpovědi bez http hlavičky v bytech
%tčas požadavku (std. formát, %{format}t podle strftime(3))
%sHTTP status požadavku
%I
%O
počet přijatých/odeslaných bytů vč. HTTP hlaviček, vyžaduje modul mod_logio

LAB: Logging

LAB: Logování

Error log and custom log

Logování chyb a přístupů

The goal is to configure error logging for entire web server and access log per virtualhosts. Access log can be joined for entire server or separated per virtualhost. It it possible to combine both approaches.

Cílem je nakonfigurovat logování chyb pro celý server a logování všech požadavků na jednotlivé virtualhosty. Logování přístupů může probíhat pro každý virtualhost zvlášť, nebo pro všechny dohromady. Možná je i kombinace.

  • Configure error log
  • Test that errors are not duplicated
  • Define custom log formats
  • Configure separate log storages for each virtualhost
  • Nakonfigurovat logování chyb
  • Ověřit neduplikování chyb
  • Definovat formáty logu přístupů
  • Nastavit úložiště logů pro jednotlivé VH

Place the configuration along main server and/or virtualhost configuration. The output buffers need to be flushed sometime during logging into files using sync command.

Konfiguraci umístěte k hlavnímu serveru a k virtuálnímu hostiteli. Při logování do souboru (pokud se zprávy neobjevují a měly by) může být potřeba vynutit vyprázdnění bufferů příkazem sync.

  1. Configure ErrorLog for entire server into /var/log/apache2/main_error_log file
  2. Configure ErrorLog for www.mycorp.net virtualhost into syslog daemon
  3. Test logging to syslog
  4. Check error messages are not duplicated in error log
  1. Pro celý server nastavte ErrorLog do souboru /var/log/apache2/main_error_log
  2. Pro virtuálního hostitele www.mycorp.net směrujte ErrorLog na syslog
  3. Ověřte, že logování na syslog funguje
  4. Ověřte, že zprávy nejsou duplikovány v ErrorLogu serveru
  1. Define following access log formats Split each filed using single space when not specified otherwise
    • my-common server IP, client (hostname), remote user, time of request arrival, request line in double-quotes, response status (final), response size in bytes (headers excluded)
    • my-referer request header Referer content, string ::, requested URL
    • my-combined concatenation of my-common and my-referer formats

    "LogFormat cannot use one nickname to define another nickname!"

  1. Definujte následující formáty vlastních logů Jednotlivá pole oddělujte mezerou, pokud není řečeno jinak
    • my-common server IP, klient (hostname), vzdálený uživatel, čas přijetí požadavku, první řádka požadavku v uvozovkách, stav požadavku (po všech přesměrováních), velikost odpovědi v bytech bez HTTP hlaviček
    • my-referer obsah hlavičky Referer odeslané serveru v požadavku, řetězec ::, požadovaná URL
    • my-combined spojení předchozích dvou formátů

    "LogFormat cannot use one nickname to define another nickname!"

  1. Configure custom access log for requests /var/log/apache2/my-access_log in my-common format /var/log/apache2/my-referer_log in my-referer format
  2. Configure custom access log in www.mycorp.net virtualhost in my-combined format using /usr/bin/logger tool, that will send messages to syslog
  3. Test logging configuration
  1. Nastavte vlastní log pro logování požadavků do /var/log/apache2/my-access_log ve formátu my-common /var/log/apache2/my-referer_log ve formátu my-referer
  2. Ve virtuálním hostiteli www.mycorp.net logujte rourou ve formátu my-combined pomocí nástroje /usr/bin/logger, který zprávy předává na syslog
  3. Ověřte funkčnost logování

Notes

Poznámky

  • Relative pathname is based on ServerRoot E.g. /etc/apache2
    • |/usr/bin/logger Logging to process
    • -t apache Tag message with apache insead of root in record
  • How to set request header using curl command
    
    									curl -H 'Referer: foo' www.mycorp.net
    								
  • Jméno souboru bez cesty bude v ServerRoot Např. /etc/apache2
    • |/usr/bin/logger Logování do procesu
    • -t apache Tag, zapíše apache místo root do logu
  • Jak nastavit hlavičku požadavku při použití příkazu curl
    
    									curl -H 'Referer: foo' www.mycorp.net
    								

MIME-type module

Modul pro práci s MIME informacemi

MIME information

MIME informace

  • Relation between meta-information and filename extension (suffix)
    • Mime-type Content-Type: image/gif
    • Language Content-Language: cs, en
    • Character set (codepage) Content-Type: text/html; charset=ISO-8859-2
    • Encoding (e.g. compression) Content-Encoding: x-gzip
  • Svázání meta-informace se souborem dle přípony
    • Mime-type Content-Type: image/gif
    • Jazyk Content-Language: cs, en
    • Znaková sada Content-Type: text/html; charset=ISO-8859-2
    • Kódování Content-Encoding: x-gzip
  • Last-Modified information stays the same when mime-type has changed
    • Response header stays the same And changes does not apply
    • The last modification time can be changed to apply mime-type change touch command can be used for this purpose
  • The extension can be stated with/out leading dot
  • The case does not matter (case-insensitive)
  • Změna mime-type neovlivňuje informaci Last-Modified
    • Hlavička odpovědi zůstane stejná A změny se neprojeví
    • Při změně mime-type změnit čas poslední modifikace Pomůže např. příkaz touch
  • Příponu lze uvádět s tečkou i bez tečky
  • Nezáleží na velikosti písmen (case-insensitive)

Multiple extensions

Více přípon (multiple extensions)

  • Mime-type derived from the last extension
  • Other meta-information derived from other extensions Language, charset, …
  • Extension lookup (comparison) one by one That can lead to unexpected results with handler processing!
  • The restriction to the last extension can help:
    
    									<FilesMatch \.cgi$>
    									  SetHandler cgi-script
    									</FilesMatch>
    								
  • Mime-type podle poslední přípony
  • Další metainformace podle ostatních přípon Jazyk, kódování, …
  • Porovnání přípon se provádí s každou zvlášť Může vést k neočekávaným výsledkům při použití handleru!
  • Omezení určení vlastností pouze na poslední příponu:
    
    									<FilesMatch \.cgi$>
    									  SetHandler cgi-script
    									</FilesMatch>
    								

							# Example: Filename = info.cs.utf8.html
							Content-Type: text/html; charset=UTF-8
							Content-Language: cs
						

							# Příklad: Soubor s názvem info.cs.utf8.html
							Content-Type: text/html; charset=UTF-8
							Content-Language: cs
						

MIME types definition

Definice MIME typů

  • Pathname to mime-type definitions
    
    									TypesConfig /etc/mime.types
    								
  • Do not edit default mime-type file Can be overwritten during server upgrade
  • Extensions are case-insensitive
  • Umístění souboru mime-type konfigurace
    
    									TypesConfig /etc/mime.types
    								
  • Výchozí soubor s mime-typy needitovat Možný přepis při upgrade serveru
  • Přípony jsou case-insensitive

							egrep '(zip|html|pdf|jpg|png|mp3)' /etc/mime.types
							...
							application/pdf                 pdf
							application/xhtml+xml           xhtml xht
							application/zip                 zip
							audio/mpeg                      mpga mpega mp2 mp3 m4a
							image/jpeg                      jpeg jpg jpe
							image/png                       png
							text/html                       html htm shtml
							...
						

MIME configuration

MIME konfigurace

  • AddType MIME-type extension… Adds relation between extension and mime-type Přidává vazbu mezi příponou (extension) a mime-typem
    
    									AddType image/gif .gif
    								
  • DefaultType MIME-type|None Specifies default mime-type (core) [ignored since 2.4.] Určuje implicitní mime-type (core) [od 2.4. se ignoruje]
    
    									DefaultType text/plain
    								
  • ForceType MIME-type|None Enforces MIME-type (core) Vynucuje nastavení MIME-type (core)
    
    									ForceType None
    								
  • RemoveType extension… Removes relation between extension and mime-type Odstraňuje vazby na příponou (extension)

MIME directives priority

Prioritizace MIME direktiv

MIME priority scheme

To disable mime-type database usage use empty file

Pro zamezení použití databáze mime-type lze použít prázdný soubor


							TypesConfig /dev/null
						

Additional MIME information

Další MIME informace

  • Language Jazyk AddLanguage MIME-lang extension…
    
    									AddLanguage cs .cz .cs
    								
    DefaultLanguage MIME-lang
    
    									DefaultLanguage en
    								
    RemoveLanguage extension…
  • Character set (codepage) Znaková sada AddCharset charset extension…
    
    									AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen
    								
    AddDefaultCharset charset Applied to text/plain or text/html only (core) Aplikuje se na text/plain, text/html (core) Takes precedence over others (META tag), use with care! Má přednost před ostatními (META tag), používat s rozmyslem!
    
    									RemoveCharset extension...
    								
  • Encoding Kódování AddEncoding MIME-enc extension…
    
    									AddEncoding x-gzip .gz
    								
    RemoveEncoding extension…
  • mod_mime_magic module
    • Guess mime-type according to first few bytes in file The same as file command
    • In case mod_mime module cannot be used to determine mime-type
    • MimeMagicFile directive enables the module
    • MimeMagicFile file
    • This module have negative impact to server performance
    
    									MimeMagicFile conf/magic
    								
  • Modul mod_mime_magic
    • Určuje mime-typ na základně prvních několika bajtů obsahu souboru Stejně jako příkaz file
    • Použití pokud není možné určit mime-typ pomocí mod_mime
    • Direktiva MimeMagicFile povoluje použití modulu
    • MimeMagicFile file
    • Použití modulu znamená další zátěž serveru
    
    									MimeMagicFile conf/magic
    								

Request processing

Zpracování požadavku

Process handling scheme Process handling scheme

Handlers

Handlery

  • AddHandler handler extension…
    
    									AddHandler cgi-script .cgi
    								
  • SetHandler handler (core)
  • RemoveHandler extension…

Input filters

Vstupní filtry

  • AddInputFilter filter[;filter…] extension…
    • Processes request data including request body - POST data
    • Adds/changes settings using SetInputFilter directive
    • Zpracovává příchozí požadavek včetně vstupu metody POST
    • Přidává/přepisuje nastavení pomocí direktivy SetInputFilter
  • SetInputFilter filter[;filter…] (core)
  • RemoveInputFilter extension…

Output filters

Výstupní filtry

  • AddOutputFilter filter[;filter…] extension…
    • Processes response
    • Adds/changes settings using SetOutputFilter directive
    • Zpracovává odchozí odpověď
    • Přidává/přepisuje nastavení pomocí direktivy SetOutputFilter
    
    									AddOutputFilter INCLUDES;DEFLATE shtml
    								
  • SetOutputFilter filter[;filter…] (core)
    
    									<Directory /www/data/>
    									  SetOutputFilter INCLUDES
    									</Directory>
    								
  • RemoveOutputFilter extension…

Content negotiation

Dojednávání obsahu

Why to negotiate (select) content

Proč dojednávání (výběr) obsahu

  • Ability to react to user preferences
  • Optional HTTP/1.1 headers - Accept*
    
    									Accept-Language: fr; q=1.0, en; q=0.5
    									Accept: text/html; q=1.0, text/*; q=0.8, q=0.6, image/jpeg; q=0.6, image/*; q=0.5, */*; q=0.1
    								
  • mod_negotiation module
  • Two mechanisms to define variants
    • Multiviews
    • Type-map
  • Dimensions of negotiation
    • Media type Accept
    • Language Accept-Language
    • Encoding Accept-Encoding
    • Charset Accept-Charset
  • Umožňuje reagovat na preference uživatele
  • Možnosti protokolu HTTP/1.1 - Hlavičky Accept*
    
    									Accept-Language: fr; q=1.0, en; q=0.5
    									Accept: text/html; q=1.0, text/*; q=0.8, q=0.6, image/jpeg; q=0.6, image/*; q=0.5, */*; q=0.1
    								
  • Modul mod_negotiation
  • Způsob činnosti
    • Multiviews
    • Type-map
  • Dimenze dojednávání
    • MIME typ Accept
    • Jazyk Accept-Language
    • Komprese Accept-Encoding
    • Kódování Accept-Charset

Content negotiation algorithm

Algoritmus pro dojednání obsahu

  1. First, for each dimension of the negotiation, check the appropriate Accept* header field and assign a quality to each variant
  2. Select the 'best' variant by a process of elimination
  3. The algorithm has now selected one 'best' variant, so return it as the response The HTTP response header Vary is set to indicate the dimensions of negotiation
  4. When no variant was selected (because none are acceptable to the client), return a 406 status Meaning "No acceptable representation"
  1. Nejdříve pro každou rovinu dojednávání zkontrolovat odpovídající hlavičku Accept* a její příslušnou kvalitu
  2. Vybrat 'nejlepší' variantu procesem eliminace
  3. Pokud algoritmus dospěl k výsledku, vrací zvolenou odpověď Včetně HTTP hlavičky odpovědi Vary obsahující dimenzi dojednávání
  4. Pokud algoritmus nedospěl k výsledku (protože žádný zdroj neodpovídal požadavkům klienta), vrací odpověď 406 "No acceptable representation"

Process of elimination

Proces eliminace

  1. Multiply resource quality and Accept quality factor
  2. Variants with the highest language quality factor
  3. Variants with the best language match, using Accept-Language or else LanguagePriority order
  4. Variants with best media type
  5. Variants with the best charset media parameters, using Accept-Charset Or Latin1, non Latin1
  6. Variants with the best encoding
  7. Variants with the smallest content length
  8. The first remaining variant first in type-map, or ASCII order
  1. Vynásobení kvality zdroje a Accept
  2. Nejlepší jazyk
  3. Pořadí jazyka v Accept-Language nebo LanguagePriority
  4. Nejlepší media type
  5. Nejlepší znaková sada Příp. Latin1, non Latin1
  6. Nejlepší kódování
  7. Nejmenší velikost obsahu
  8. První zbývající možnost Podle type-map, nebo ASCII pořadí

Multiviews

  • Enabled by Multiviews option
    
    									Options +Multiviews
    								
  • Configuration using MultiviewsMatch directive (mod_mime)
    
    									MultiviewsMatch Any | NegotiatedOnly | Filters | Handlers
    								
    • NegotiatedOnly Content-Type/Language/Encoding must match (default)
    • Filters, Handlers Filters / handlers taken into account as well
    • Any Processes files with any extension
  • Povolení nastavením volby Multiviews
    
    									Options +Multiviews
    								
  • Nastavení čínnosti direktivou MultiviewsMatch (mod_mime)
    
    									MultiviewsMatch Any | NegotiatedOnly | Filters | Handlers
    								
    • NegotiatedOnly Musí odpovídat Content-Type/Language/Encoding (default)
    • Filters, Handlers Zpracovává přípony asociované s filtry / handlery
    • Any Zpracovává soubory s libovolnou příponou
  • Server language priority configuration
    • LanguagePriority MIME-lang [MIME-lang]
      
      											LanguagePriority cs en de fr
      										
    • ForceLanguagePriority None | Prefer | Fallback
      
      											# According to LanguagePriority
      											ForceLanguagePriority Prefer
      										
  • Nastavení preferencí jazyka serveru
    • LanguagePriority MIME-lang [MIME-lang]
      
      											LanguagePriority cs en de fr
      										
    • ForceLanguagePriority None | Prefer | Fallback
      
      											# Podle LanguagePriority
      											ForceLanguagePriority Prefer
      										

Type-map

  • This file should have an entry for each available variant (filename) Default extension: .var
    • Separated by blank lines
    • Source quality parameter qs=<0.0,1.0>
    • Headers Content-Type/Language/Encoding
  • Processed by type-map handler
    
    									AddHandler type-map .var
    								
    
    									URI: text.html
    
    									URI: text.html.cs
    									Content-Language: cs-cz
    									Content-Type: text/html; qs=0.8
    
    									URI: text.html.en
    									Content-Language: en-us
    									Content-Type: text/html; qs=1
    								
  • Soubor obsahující varianty jména souborů Obvykle .var
    • Oddělovač položek prázdný řádek
    • Kvalita zdroje parametr qs=<0.0,1.0>
    • Položka Content-Type/Language/Encoding
  • Zpracování handlerem type-map
    
    									AddHandler type-map .var
    								
    
    									URI: text.html
    
    									URI: text.html.cs
    									Content-Language: cs-cz
    									Content-Type: text/html; qs=0.8
    
    									URI: text.html.en
    									Content-Language: en-us
    									Content-Type: text/html; qs=1
    								

Response data compression

Komprese odesílaných dat

  • Only when Web browser (client) supports encoding Accept-Encoding: gzip,deflate Else server sends uncompressed data
  • When mod_mime and mod_deflate are enabled
    
    									AddType text/plain .log
    									AddOutputFilter DEFLATE .log
    									AddOutputFilterByType DEFLATE text/html text/plain
    								
  • DeflateCompressionLevel 1 = low compression, 9 = high compression
  • Prohlížeč (klient) musí podporovat kódování Accept-Encoding: gzip,deflate Jinak server pošle nekomprimovaná data
  • V případě použití mod_mime a mod_deflate
    
    									AddType text/plain .log
    									AddOutputFilter DEFLATE .log
    									AddOutputFilterByType DEFLATE text/html text/plain
    								
  • DeflateCompressionLevel Stupeň komprese 1 = nejméně komprese, 9 = nejvíce komprese

Compression logging

Logování komprese

  • Compression information as notes Additional logging notes names that can be used in CustomLog %{name}n Informace o kompresi Přidává další možnosti jako typ poznámky %{název}n
    
    									DeflateFilterNote Input instream
    									DeflateFilterNote Output outstream
    									DeflateFilterNote Ratio ratio
    									LogFormat "%{outstream}n/%{instream}n (%{ratio}n%%)" …
    								

LAB: Content negotiation

LAB: Dojednávání obsahu

Content negotiation

Dojednávání obsahu

The goal is to configure content negotiation using Multiviews and using Type-map as well. The part of it is also a configuration of preferred language variants according to client needs and server abilities.

Cílem je nakonfigurovat dojednávání obsahu pomocí Multiviews i pomocí Type-map. Součástí je také nastavení preferovaných jazykových variant podle přání klienta i možností serveru.

  • Configure C/N using file extensions (Multiviews)
  • Configure C/N using Type-map files
  • Configure server language priorities and server behavior
  • Nastavit dojednání s využitím přípon souborů (Multiviews)
  • Nastavit dojednání s využitím Type-map souborů
  • Nastavit jazykové preference serveru a respektování potřeb klienta
  1. Check existence of index.html.{en,de} files in /var/www/main/manual directory and set /manual alias for that directory
  2. Configure server to provide content negotiation in case of index.html requests according to client language preferences Change preferred language in web browser or add request header
    1. Configure C/N using Type-map file
    2. Configure C/N using Multiviews method
  1. V adresáři /var/www/main/manual zkontrolujte existenci a obsah souborů index.html.{en,de} a nastavte alias /manual pro tento adresář
  2. Nastavte direktivy příslušných modulů tak, aby vracely jazykové varianty při požadavku na soubor index.html v závislosti na požadavcích klienta Změňte v prohlížeči národní prostředí, případně odesílané hlavičky požadavků
    1. Využijte výběr varianty na základě type-map
    2. Využijte výběr varianty na Multiviews

Tips

Tipy

  • 
    									curl -I -H 'Accept-Language: de' …
    								
  • 
    									<Directory /var/www/main/manual>
    									  <FilesMatch "\.html$">
    									    SetHandler type-map
    									  </FilesMatch>
    									</Directory>
    								
  • 
    									Options +Multiviews
    
    									mv index.html index-bak.html
    								
  1. Use relevant directives to ensure language selection will work even if preferred language variant is unavailable
  2. Try to use ForceLanguagePriority and LanguagePriority directives and see a corresponding server behavior
  1. Nastavte direktivy tak, aby výběr fungoval i pro případ, že nebude požadovaná varianta k dispozici
  2. Vyzkoušejte vliv nastavení direktiv ForceLanguagePriority a LanguagePriority na přání klienta a možnosti serveru

Server behavior for different settings

Chování při různém nastavení

ForceLanguagePriority unset
language
unavailable
language
Prefer LanguagePriority 406
Fallback smallest LanguagePriority
Fallback Prefer LanguagePriority LanguagePriority
Prefer Fallback LanguagePriority LanguagePriority
None smallest 406
ForceLanguagePriority žádný
jazyk
neexistující
jazyk
Prefer LanguagePriority 406
Fallback nejmenší LanguagePriority
Fallback Prefer LanguagePriority LanguagePriority
Prefer Fallback LanguagePriority LanguagePriority
None nejmenší 406
  1. Try to send compressed data in case a client does support it
  2. Create a log file that will store transferred data sizes (compressed and uncompressed)
  3. Create a script to print out the data compression efficiency (ratio)
  1. Otestujte možnost odesílání komprimovaných dat klientovi, jenž to umožňuje
  2. Vytvořte log soubor, do kterého se budou ukládat informace o přenášených datech (nekomprimovaných, komprimovaných)
  3. Vytvořte skript, který bude zjišťovat úspěšnost komprese přenášených dat