Mercurial > hg > nginx-site
changeset 936:99f8165723ca
Beginner's guide.
author | Ruslan Ermilov <ru@nginx.com> |
---|---|
date | Tue, 25 Jun 2013 10:39:32 +0400 |
parents | 3860b37d56c0 |
children | c1751a5e538a |
files | xml/en/GNUmakefile xml/en/docs/beginners_guide.xml xml/en/docs/index.xml xml/ru/GNUmakefile xml/ru/docs/beginners_guide.xml xml/ru/docs/index.xml |
diffstat | 6 files changed, 965 insertions(+), 2 deletions(-) [+] |
line wrap: on
line diff
--- a/xml/en/GNUmakefile +++ b/xml/en/GNUmakefile @@ -18,6 +18,7 @@ DOCS = \ howto_setup_development_environment_on_ec2 \ nginx_dtrace_pid_provider \ contributing_changes \ + beginners_guide \ configure \ FAQ = \
new file mode 100644 --- /dev/null +++ b/xml/en/docs/beginners_guide.xml @@ -0,0 +1,471 @@ +<!-- + Copyright (C) Nginx, Inc. + --> + +<!DOCTYPE article SYSTEM "../../../dtd/article.dtd"> + +<article name="Beginner’s Guide" + link="/en/docs/beginners_guide.html" + lang="en" + rev="1"> + +<section> + +<para> +This guide gives a basic introduction to nginx and describes some +simple tasks that can be done with it. +It is supposed that nginx is already installed on the reader’s machine. +If it is not, see the <link doc="install.xml"/> page. +This guide describes how to start and stop nginx, and reload its +configuration, explains the structure +of the configuration file and describes how to set up nginx +to serve out static content, how to configure nginx as a proxy +server, and how to connect it with a FastCGI application. +</para> + +<para> +nginx has one master process and several worker processes. +The main purpose of the master process is to read and evaluate configuration, +and maintain worker processes. +Worker processes do actual processing of requests. +nginx employs event-based model and OS-dependent mechanisms to efficiently +distribute requests among worker processes. +The number of worker processes is defined in the configuration file and +may be fixed for a given configuration or automatically adjusted to the +number of available CPU cores (see +<link doc="ngx_core_module.xml" id="worker_processes"/>). +</para> + +<para> +The way nginx and its modules work is determined in the configuration file. +By default, the configuration file is named <path>nginx.conf</path> +and placed in the directory +<path>/usr/local/nginx/conf</path>, +<path>/etc/nginx</path>, or +<path>/usr/local/etc/nginx</path>. +</para> + +</section> + + +<section id="control" name="Starting, Stopping, and Reloading Configuration"> + +<para> +To start nginx, run the executable file. +Once nginx is started, it can be controlled by invoking the executable +with the <literal>-s</literal> parameter. +Use the following syntax: +<programlisting> +nginx -s <i>signal</i> +</programlisting> +Where <i>signal</i> may be one of the following: +<list type="bullet"> +<listitem> +<literal>stop</literal>—fast shutdown +</listitem> +<listitem> +<literal>quit</literal>—graceful shutdown +</listitem> +<listitem> +<literal>reload</literal>—reloading the configuration file +</listitem> +<listitem> +<literal>reopen</literal>—reopening the log files +</listitem> +</list> +For example, to stop nginx processes with waiting for the worker processes +to finish serving current requests, the following command can be executed: +<programlisting> +nginx -s quit +</programlisting> +<note>This command should be executed under the same user that +started nginx.</note> +</para> + +<para> +Changes made in the configuration file +will not be applied until the command to reload configuration is +sent to nginx or it is restarted. +To reload configuration, execute: +<programlisting> +nginx -s reload +</programlisting> +</para> + +<para> +Once the master process receives the signal to reload configuration, +it checks the syntax validity +of the new configuration file and tries to apply the configuration provided +in it. +If this is a success, the master process starts new worker processes +and sends messages to old worker processes, requesting them to +shut down. +Otherwise, the master process rolls back the changes and +continues to work with the old configuration. +Old worker processes, receiving a command to shut down, +stop accepting new connections and continue to service current requests until +all such requests are serviced. +After that, the old worker processes exit. +</para> + +<para> +A signal may also be sent to nginx processes with the help of Unix tools +such as the <command>kill</command> utility. +In this case a signal is sent directly to a process with a given process ID. +The process ID of the nginx master process is written, by default, to the +<path>nginx.pid</path> in the directory +<path>/usr/local/nginx/logs</path> or +<path>/var/run</path>. +For example, if the master process ID is 1628, to send the QUIT signal +resulting in nginx’s graceful shutdown, execute: +<programlisting> +kill -s QUIT 1628 +</programlisting> +For getting the list of all running nginx processes, the <command>ps</command> +utility may be used, for example, in the following way: +<programlisting> +ps -ax | grep nginx +</programlisting> +For more information on sending signals to nginx, see +<link doc="control.xml"/>. +</para> + +</section> + + +<section id="conf_structure" name="Configuration File’s Structure"> + +<para> +nginx consists of modules which are controlled by directives specified +in the configuration file. +Directives are divided into simple directives and block directives. +A simple directive consists of the name and parameters separated by spaces +and ends with a semicolon (<literal>;</literal>). +A block directive has the same structure as a simple directive, but +instead of the semicolon it ends with a set of additional instructions +surrounded by braces (<literal>{</literal> and <literal>}</literal>). +If a block directive can have other directives inside braces, +it is called a context (examples: +<link doc="ngx_core_module.xml" id="events"/>, +<link doc="http/ngx_http_core_module.xml" id="http"/>, +<link doc="http/ngx_http_core_module.xml" id="server"/>, +and +<link doc="http/ngx_http_core_module.xml" id="location"/>). +</para> + +<para> +Directives placed in the configuration file outside +of any contexts are considered to be in the +<link doc="ngx_core_module.xml">main</link> context. +The <literal>events</literal> and <literal>http</literal> directives +reside in the <literal>main</literal> context, <literal>server</literal> +in <literal>http</literal>, and <literal>location</literal> in +<literal>server</literal>. +</para> + +<para> +The rest of a line after the <literal>#</literal> sign is considered a comment. +</para> + +</section> + + +<section id="static" name="Serving Static Content"> + +<para> +An important web server task is serving out +files (such as images or static HTML pages). +You will implement an example where, depending on the request, +files will be served from different local directories: <path>/data/www</path> +(which may contain HTML files) and <path>/data/images</path> +(containing images). +This will require editing of the configuration file and setting up of a +<link doc="http/ngx_http_core_module.xml" id="server"/> +block inside the <link doc="http/ngx_http_core_module.xml" id="http"/> +block with two <link doc="http/ngx_http_core_module.xml" id="location"/> +blocks. +</para> + +<para> +First, create the <path>/data/www</path> directory and put an +<path>index.html</path> file with any text content into it and +create the <path>/data/images</path> directory and place some +images in it. +</para> + +<para> +Next, open the configuration file. +The default configuration file already includes several examples of +the <literal>server</literal> block, mostly commented out. +For now comment out all such blocks and start a new +<literal>server</literal> block: +<programlisting> +http { + server { + } +} +</programlisting> +Generally, the configuration file may include several +<literal>server</literal> blocks +<link doc="http/request_processing.xml">distinguished</link> by ports on which +they <link doc="http/ngx_http_core_module.xml" id="listen">listen</link> to +and by +<link doc="http/server_names.xml">server names</link>. +Once nginx decides which <literal>server</literal> processes a request, +it tests the URI specified in the request’s header against the parameters of the +<literal>location</literal> directives defined inside the +<literal>server</literal> block. +</para> + +<para> +Add the following <literal>location</literal> block to the +<literal>server</literal> block: +<programlisting> +location / { + root /data/www; +} +</programlisting> +This <literal>location</literal> block specifies the +“<path>/</path>” prefix compared with the URI from the request. +For matching requests, the URI will be added to the path specified in the +<link doc="http/ngx_http_core_module.xml" id="root"/> +directive, that is, to <path>/data/www</path>, +to form the path to the requested file on the local file system. +If there are several matching <literal>location</literal> blocks nginx +selects the one with the longest prefix. +The <literal>location</literal> block above provides the shortest +prefix, of length one, +and so only if all other <literal>location</literal> +blocks fail to provide a match, this block will be used. +</para> + +<para> +Next, add the second <literal>location</literal> block: +<programlisting> +location /images/ { + root /data; +} +</programlisting> +It will be a match for requests starting with <literal>/images/</literal> +(<literal>location /</literal> also matches such requests, +but has shorter prefix). +</para> + +<para> +The resulting configuration of the <literal>server</literal> block should +look like this: +<programlisting> +server { + location / { + root /data/www; + } + + location /images/ { + root /data; + } +} +</programlisting> +This is already a working configuration of a server that listens +on the standard port 80 and is accessible on the local machine at +<literal>http://localhost/</literal>. +In response to requests with URIs starting with <literal>/images/</literal>, +the server will send files from the <path>/data/images</path> directory. +For example, in response to the +<literal>http://localhost/images/example.png</literal> request nginx will +send the <path>/data/images/example.png</path> file. +If such file does not exist, nginx will send a response +indicating the 404 error. +Requests with URIs not starting with <literal>/images/</literal> will be +mapped onto the <path>/data/www</path> directory. +For example, in response to the +<literal>http://localhost/some/example.html</literal> request nginx will +send the <path>/data/www/some/example.html</path> file. +</para> + +<para> +To apply the new configuration, start nginx if it is not yet started or +send the <literal>reload</literal> signal to the nginx’s master process, +by executing: +<programlisting> +nginx -s reload +</programlisting> +</para> + +<para> +<note> +In case something does not work as expected, you may try to find out +the reason in <path>access.log</path> and +<path>error.log</path> files in the directory +<path>/usr/local/nginx/logs</path> or +<path>/var/log/nginx</path>. +</note> +</para> + +</section> + + +<section id="proxy" name="Setting Up a Simple Proxy Server"> + +<para> +One of the frequent uses of nginx is setting it up as a proxy server, which +means a server that receives requests, passes them to the proxied servers, +retrieves responses from them, and sends them to the clients. +</para> + +<para> +We will configure a basic proxy server, which serves requests of +images with files from the local directory and sends all other requests to a +proxied server. +In this example, both servers will be defined on a single nginx instance. +</para> + +<para> +First, define the proxied server by adding one more <literal>server</literal> +block to the nginx’s configuration file with the following contents: +<programlisting> +server { + listen 8080; + root /data/up1; + + location / { + } +} +</programlisting> +This will be a simple server that listens on the port 8080 +(previously, the <literal>listen</literal> directive has not been specified +since the standard port 80 was used) and maps +all requests to the <path>/data/up1</path> directory on the local +file system. +Create this directory and put the <path>index.html</path> file into it. +Note that the <literal>root</literal> directive is placed in the +<literal>server</literal> context. +Such <literal>root</literal> directive is used when the +<literal>location</literal> block selected for serving a request does not +include own <literal>root</literal> directive. +</para> + +<para> +Next, use the server configuration from the previous section +and modify it to make it a proxy server configuration. +In the first <literal>location</literal> block, put the +<link doc="http/ngx_http_proxy_module.xml" id="proxy_pass"/> +directive with the protocol, name and port of the proxied server specified +in the parameter (in our case, it is <literal>http://localhost:8080</literal>): +<programlisting> +server { + location / { + proxy_pass http://localhost:8080; + } + + location /images/ { + root /data; + } +} +</programlisting> +</para> + +<para> +We will modify the second <literal>location</literal> +block, which currently maps requests with the <literal>/images/</literal> +prefix to the files under the <path>/data/images</path> directory, +to make it match the requests of images with typical file extensions. +The modified <literal>location</literal> block looks like this: +<programlisting> +location ~ \.(gif|jpg|png)$ { + root /data/images; +} +</programlisting> +The parameter is a regular expression matching all URIs ending +with <path>.gif</path>, <path>.jpg</path>, or <path>.png</path>. +A regular expression should be preceded with <literal>~</literal>. +The corresponding requests will be mapped to the <path>/data/images</path> +directory. +</para> + +<para> +When nginx selects a <literal>location</literal> block to serve a request +it first checks <link doc="http/ngx_http_core_module.xml" id="location"/> +directives that specify prefixes, remembering <literal>location</literal> +with the longest prefix, and then checks regular expressions. +If there is a match with a regular expression, nginx picks this +<literal>location</literal> or, otherwise, it picks the one remembered earlier. +</para> + +<para> +The resulting configuration of a proxy server will look like this: +<programlisting> +server { + location / { + proxy_pass http://localhost:8080/; + } + + location ~ \.(gif|jpg|png)$ { + root /data/images; + } +} +</programlisting> +This server will filter requests ending with <path>.gif</path>, +<path>.jpg</path>, or <path>.png</path> +and map them to the <path>/data/images</path> directory (by adding URI to the +<literal>root</literal> directive’s parameter) and pass all other requests +to the proxied server configured above. +</para> + +<para> +To apply new configuration, send the <literal>reload</literal> signal to +nginx as described in the previous sections. +</para> + +<para> +There are many <link doc="http/ngx_http_proxy_module.xml">more</link> +directives that may be used to further configure a proxy connection. +</para> + +</section> + + +<section id="fastcgi" name="Setting Up FastCGI Proxying"> + +<para> +nginx can be used to route requests to FastCGI servers which run +applications built with various frameworks and programming languages +such as PHP. +</para> + +<para> +The most basic nginx configuration to work with a FastCGI server +includes using the +<link doc="http/ngx_http_fastcgi_module.xml" id="fastcgi_pass"/> +directive instead of the <literal>proxy_pass</literal> directive, +and <link doc="http/ngx_http_fastcgi_module.xml" id="fastcgi_param"/> +directives to set parameters passed to a FastCGI server. +Suppose the FastCGI server is accessible on <literal>localhost:9000</literal>. +Taking the proxy configuration from the previous section as a basis, +replace the <literal>proxy_pass</literal> directive with the +<literal>fastcgi_pass</literal> directive and change the parameter to +<literal>localhost:9000</literal>. +In PHP, the <literal>SCRIPT_FILENAME</literal> parameter is used for +determining the script name, and the <literal>QUERY_STRING</literal> +parameter is used to pass request parameters. +The resulting configuration would be: +<programlisting> +server { + location / { + fastcgi_pass localhost:9000; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + fastcgi_param QUERY_STRING $query_string; + } + + location ~ \.(gif|jpg|png)$ { + root /data/images; + } +} +</programlisting> +This will set up a server that will route all requests except for +requests for static images to the proxied server operating on +<literal>localhost:9000</literal> through the FastCGI protocol. +</para> + +</section> + +</article>
--- a/xml/en/docs/index.xml +++ b/xml/en/docs/index.xml @@ -8,7 +8,7 @@ <article name="nginx documentation" link="/en/docs/" lang="en" - rev="7" + rev="8" toc="no"> @@ -22,6 +22,10 @@ </listitem> <listitem> +<link doc="beginners_guide.xml"/> +</listitem> + +<listitem> <link doc="control.xml"/> </listitem>
--- a/xml/ru/GNUmakefile +++ b/xml/ru/GNUmakefile @@ -15,6 +15,7 @@ DOCS = \ debugging_log \ http/websocket \ contributing_changes \ + beginners_guide \ configure \ FAQ = \
new file mode 100644 --- /dev/null +++ b/xml/ru/docs/beginners_guide.xml @@ -0,0 +1,482 @@ +<!-- + Copyright (C) Nginx, Inc. + --> + +<!DOCTYPE article SYSTEM "../../../dtd/article.dtd"> + +<article name="Руководство для начинающих" + link="/ru/docs/beginners_guide.html" + lang="ru" + rev="1"> + +<section> + +<para> +В этом руководстве даётся начальное введение в nginx и описываются +некоторые простые задачи, которые могут быть решены с его помощью. +Предполагается, что nginx уже установлен на компьютере читателя. +Если нет, см. <link doc="install.xml"/>. +В этом руководстве описывается, как запустить и остановить nginx +и перезагрузить его конфигурацию, +объясняется, как устроен конфигурационный файл, и описывается, +как настроить nginx для раздачи статического содержимого, как +настроить прокси-сервер на nginx, и как связать nginx с приложением +FastCGI. +</para> + +<para> +У nginx есть один главный и несколько рабочих процессов. +Основная задача главного процесса — чтение и проверка конфигурации +и управление рабочими процессами. +Рабочие процессы выполняют фактическую обработку запросов. +nginx использует +модель, основанную на событиях, и зависящие от операционной системы +механизмы для эффективного распределения запросов между рабочими процессами. +Количество рабочих процессов задаётся в конфигурационном файле и +может быть фиксированным для данной конфигурации или автоматически +устанавливаться равным числу доступных процессорных ядер (см. +<link doc="ngx_core_module.xml" id="worker_processes"/>). +</para> + +<para> +Как работают nginx и его модули, определяется в конфигурационном файле. +По умолчанию, конфигурационный файл называется <path>nginx.conf</path> +и расположен в каталоге +<path>/usr/local/nginx/conf</path>, +<path>/etc/nginx</path> или +<path>/usr/local/etc/nginx</path>. +</para> + +</section> + + +<section id="control" name="Запуск, остановка, перезагрузка конфигурации"> + +<para> +Чтобы запустить nginx, нужно выполнить исполняемый файл. +Когда nginx запущен, им можно управлять, вызывая исполняемый файл с +параметром <literal>-s</literal>. +Используйте следующий синтаксис: +<programlisting> +nginx -s <i>сигнал</i> +</programlisting> +Где <i>сигнал</i> может быть одним их нижеследующего: +<list type="bullet"> +<listitem> +<literal>stop</literal>—быстрое завершение +</listitem> +<listitem> +<literal>quit</literal>—плавное завершение +</listitem> +<listitem> +<literal>reload</literal>—перезагрузка конфигурационного файла +</listitem> +<listitem> +<literal>reopen</literal>—переоткрытие лог-файлов +</listitem> +</list> +Например, чтобы остановить процессы nginx с ожиданием окончания +обслуживания текущих запросов рабочими процессами, можно выполнить +следующую команду: +<programlisting> +nginx -s quit +</programlisting> +<note>Команда должна быть выполнена под тем же +пользователем, под которым был запущен nginx.</note> +</para> + +<para> +Изменения, сделанные в конфигурационном файле, +не будут применены, пока команда перезагрузить конфигурацию не будет +вручную отправлена nginx’у или он не будет перезапущен. +Для перезагрузки конфигурации выполните: +<programlisting> +nginx -s reload +</programlisting> +</para> + +<para> +Получив сигнал, главный процесс проверяет правильность синтаксиса нового +конфигурационного файла и пытается применить конфигурацию, содержащуюся +в нём. +Если это ему удаётся, главный процесс запускает новые рабочие процессы +и отправляет сообщения старым рабочим процессам с требованием завершиться. +В противном случае, главный процесс откатывает изменения и продолжает +работать со старой конфигурацией. +Старые рабочие процессы, получив команду завершиться, +прекращают принимать новые запросы и продолжают обслуживать текущие запросы +до тех пор, пока все такие запросы не будут обслужены. +После это старые рабочие процессы завершаются. +</para> + +<para> +Посылать сигналы процессам nginx можно также средствами Unix, +такими как утилита <command>kill</command>. +В этом случае сигнал отправляется напрямую процессу с данным ID. +ID главного процесса nginx записывается по умолчанию в файл +<path>nginx.pid</path> в каталоге +<path>/usr/local/nginx/logs</path> или +<path>/var/run</path>. +Например, если ID главного процесса равен 1628, для отправки сигнала QUIT, +который приведёт к плавному завершению nginx, нужно выполнить: +<programlisting> +kill -s QUIT 1628 +</programlisting> +Для просмотра списка всех запущенных процессов nginx может быть использована +утилита <command>ps</command>, например, следующим образом: +<programlisting> +ps -ax | grep nginx +</programlisting> +Дополнительную информацию об отправке сигналов процессам nginx +можно найти в <link doc="control.xml"/>. +</para> + +</section> + + +<section id="conf_structure" name="Структура конфигурационного файла"> + +<para> +nginx состоит из модулей, которые настраиваются директивами, указанными +в конфигурационном файле. +Директивы делятся на простые и блочные. +Простая директива состоит из имени и параметров, разделённых пробелами, +и оканчивается точкой с запятой (<literal>;</literal>). +Блочная директива устроена так же, как и простая директива, но +вместо точки с запятой после имени и параметров следует набор дополнительных +инструкций, помещённых внутри фигурных скобок +(<literal>{</literal> и <literal>}</literal>). +Если у блочной директивы внутри фигурных скобок можно задавать другие +директивы, то она называется контекстом (примеры: +<link doc="ngx_core_module.xml" id="events"/>, +<link doc="http/ngx_http_core_module.xml" id="http"/>, +<link doc="http/ngx_http_core_module.xml" id="server"/> +и +<link doc="http/ngx_http_core_module.xml" id="location"/>). +</para> + +<para> +Директивы, помещённые в конфигурационном файле вне любого контекста, +считаются находящимися в контексте +<link doc="ngx_core_module.xml">main</link>. +Директивы <literal>events</literal> и <literal>http</literal> +располагаются в контексте <literal>main</literal>, <literal>server</literal> — +в <literal>http</literal>, а <literal>location</literal> — в +<literal>server</literal>. +</para> + +<para> +Часть строки после символа <literal>#</literal> считается комментарием. +</para> + +</section> + + +<section id="static" name="Раздача статического содержимого"> + +<para> +Одна из важных задач конфигурации nginx — раздача +файлов, таких как изображения или статические HTML-страницы. +Рассмотрим пример, в котором в зависимости от запроса файлы будут +раздаваться из разных локальных каталогов: <path>/data/www</path>, +который содержит HTML-файлы, и <path>/data/images</path>, +содержащий файлы с изображениями. +Для этого потребуется отредактировать конфигурационный файл и настроить +блок +<link doc="http/ngx_http_core_module.xml" id="server"/> +внутри блока <link doc="http/ngx_http_core_module.xml" id="http"/> +с двумя блоками <link doc="http/ngx_http_core_module.xml" id="location"/>. +</para> + +<para> +Во-первых, создайте каталог <path>/data/www</path> и положите в него файл +<path>index.html</path> с любым текстовым содержанием, а также +создайте каталог <path>/data/images</path> и положите в него несколько +файлов с изображениями. +</para> + +<para> +Далее, откройте конфигурационный файл. +Конфигурационный файл по умолчанию уже включает в себя несколько +примеров блока <literal>server</literal>, большей частью закомментированных. +Для нашей текущей задачи лучше закомментировать все такие блоки и +добавить новый блок <literal>server</literal>: +<programlisting> +http { + server { + } +} +</programlisting> +В общем случае конфигурационный файл может содержать несколько блоков +<literal>server</literal>, +<link doc="http/request_processing.xml">различаемых</link> по портам, на +которых они +<link doc="http/ngx_http_core_module.xml" id="listen">слушают</link>, +и по +<link doc="http/server_names.xml">имени сервера</link>. +Определив, какой <literal>server</literal> будет обрабатывать запрос, +nginx сравнивает URI, указанный в заголовке запроса, с параметрами директив +<literal>location</literal>, определённых внутри блока +<literal>server</literal>. +</para> + +<para> +В блок <literal>server</literal> добавьте блок <literal>location</literal> +следующего вида: +<programlisting> +location / { + root /data/www; +} +</programlisting> +Этот блок <literal>location</literal> задаёт “<path>/</path>” +в качестве префикса, который сравнивается с URI из запроса. +Для подходящих запросов добавлением URI к пути, указанному в директиве +<link doc="http/ngx_http_core_module.xml" id="root"/>, +то есть, в данном случае, к <path>/data/www</path>, получается +путь к запрашиваемому файлу в локальной файловой системе. +Если есть совпадение с несколькими блоками <literal>location</literal>, +nginx выбирает блок c самым длинным префиксом. +В блоке <literal>location</literal> выше указан самый короткий префикс, +длины один, +и поэтому этот блок будет использован, только если не будет совпадения +ни с одним из остальных блоков <literal>location</literal>. +</para> + +<para> +Далее, добавьте второй блок <literal>location</literal>: +<programlisting> +location /images/ { + root /data; +} +</programlisting> +Он будет давать совпадение с запросами, начинающимися с +<literal>/images/</literal> +(<literal>location /</literal> для них тоже подходит, но указанный там префикс +короче). +</para> + +<para> +Итоговая конфигурация блока <literal>server</literal> должна выглядеть +следующим образом: +<programlisting> +server { + location / { + root /data/www; + } + + location /images/ { + root /data; + } +} +</programlisting> +Это уже работающая конфигурация сервера, слушающего на стандартном порту 80 +и доступного на локальном компьютере по адресу +<literal>http://localhost/</literal>. +В ответ на запросы, URI которых начинаются с <literal>/images/</literal>, +сервер будет отправлять файлы из каталога <path>/data/images</path>. +Например, на запрос +<literal>http://localhost/images/example.png</literal> nginx отправит +в ответ файл <path>/data/images/example.png</path>. +Если же этот файл не существует, nginx отправит ответ, указывающий на +ошибку 404. +Запросы, URI которых не начинаются на <literal>/images/</literal>, будут +отображены на каталог <path>/data/www</path>. +Например, в результате запроса +<literal>http://localhost/some/example.html</literal> в ответ будет +отправлен файл <path>/data/www/some/example.html</path>. +</para> + +<para> +Чтобы применить новую конфигурацию, запустите nginx, если он ещё не запущен, +или отправьте сигнал <literal>reload</literal> главному процессу nginx, +выполнив: +<programlisting> +nginx -s reload +</programlisting> +</para> + +<para> +<note> +В случае если что-то работает не как ожидалось, можно попытаться выяснить +причину с помощью файлов <path>access.log</path> и <path>error.log</path> +из каталога +<path>/usr/local/nginx/logs</path> или +<path>/var/log/nginx</path>. +</note> +</para> + +</section> + + +<section id="proxy" name="Настройка простого прокси-сервера"> + +<para> +Одним из частых применений nginx является использование его в качестве +прокси-сервера, то есть сервера, который принимает запросы, перенаправляет их +на проксируемые сервера, получает ответы от них и отправляет их клиенту. +</para> + +<para> +Мы настроим базовый прокси-сервер, который будет обслуживать запросы +изображений из локального каталога и отправлять все остальные запросы на +проксируемый сервер. +В этом примере оба сервера будут работать в рамках одного +экземпляра nginx. +</para> + +<para> +Во-первых, создайте проксируемый сервер, добавив ещё один блок +<literal>server</literal> в конфигурационный файл nginx со следующим +содержимым: +<programlisting> +server { + listen 8080; + root /data/up1; + + location / { + } +} +</programlisting> +Это будет простой сервер, слушающий на порту 8080 +(ранее директива <literal>listen</literal> не указывалась, потому что +использовался стандартный порт 80) и отображающий все +запросы на каталог <path>/data/up1</path> в локальной файловой +системе. +Создайте этот каталог и положите в него файл <path>index.html</path>. +Обратите внимание, что директива <literal>root</literal> помещена в контекст +<literal>server</literal>. +Такая директива <literal>root</literal> будет использована, когда директива +<literal>location</literal>, выбранная для выполнения запроса, не содержит +собственной директивы <literal>root</literal>. +</para> + +<para> +Далее, используйте конфигурацию сервера из предыдущего раздела +и видоизмените её, превратив в конфигурацию прокси-сервера. +В первый блок <literal>location</literal> добавьте директиву +<link doc="http/ngx_http_proxy_module.xml" id="proxy_pass"/>, +указав протокол, имя и порт проксируемого сервера в качестве параметра +(в нашем случае это <literal>http://localhost:8080</literal>): +<programlisting> +server { + location / { + proxy_pass http://localhost:8080; + } + + location /images/ { + root /data; + } +} +</programlisting> +</para> + +<para> +Мы изменим второй блок +<literal>location</literal>, который на данный момент отображает запросы +с префиксом <literal>/images/</literal> на файлы из каталога +<path>/data/images</path> так, чтобы он подходил для запросов изображений +с типичными расширениями файлов. +Изменённый блок <literal>location</literal> выглядит следующим образом: +<programlisting> +location ~ \.(gif|jpg|png)$ { + root /data/images; +} +</programlisting> +Параметром является регулярное выражение, дающее совпадение со всеми +URI, оканчивающимися на <path>.gif</path>, <path>.jpg</path> или +<path>.png</path>. +Регулярному выражению должен предшествовать символ <literal>~</literal>. +Соответствующие запросы будут отображены на каталог <path>/data/images</path>. +</para> + +<para> +Когда nginx выбирает блок <literal>location</literal>, +который будет обслуживать запрос, то вначале он проверяет +директивы <link doc="http/ngx_http_core_module.xml" id="location"/>, +задающие префиксы, запоминая <literal>location</literal> с самым +длинным подходящим префиксом, а затем проверяет регулярные выражения. +Если есть совпадение с регулярным выражением, nginx выбирает соответствующий +<literal>location</literal>, в противном случае берётся запомненный ранее +<literal>location</literal>. +</para> + +<para> +Итоговая конфигурация прокси-сервера выглядит следующим образом: +<programlisting> +server { + location / { + proxy_pass http://localhost:8080/; + } + + location ~ \.(gif|jpg|png)$ { + root /data/images; + } +} +</programlisting> +Этот сервер будет фильтровать запросы, оканчивающиеся на +<path>.gif</path>, <path>.jpg</path> или <path>.png</path>, +и отображать их на каталог <path>/data/images</path> (добавлением URI к +параметру директивы <literal>root</literal>) и перенаправлять все остальные +запросы на проксируемый сервер, сконфигурированный выше. +</para> + +<para> +Чтобы применить новую конфигурацию, отправьте сигнал <literal>reload</literal> +nginx’у, как описывалось в предыдущих разделах. +</para> + +<para> +Существует <link doc="http/ngx_http_proxy_module.xml">множество</link> +других директив для дальнейшей настройки прокси-соединения. +</para> + +</section> + + +<section id="fastcgi" name="Настройка проксирования FastCGI"> + +<para> +nginx можно использовать для перенаправления запросов на FastCGI-серверы. +На них могут исполняться приложения, созданные с использованием +разнообразных фреймворков и языков программирования, например, PHP. +</para> + +<para> +Базовая конфигурация nginx для работы с проксируемым FastCGI-сервером +включает в себя использование директивы +<link doc="http/ngx_http_fastcgi_module.xml" id="fastcgi_pass"/> +вместо директивы <literal>proxy_pass</literal>, +и директив <link doc="http/ngx_http_fastcgi_module.xml" id="fastcgi_param"/> +для настройки параметров, передаваемых FastCGI-серверу. +Представьте, что FastCGI-сервер доступен по адресу +<literal>localhost:9000</literal>. +Взяв за основу конфигурацию прокси-сервера из предыдущего раздела, +замените директиву <literal>proxy_pass</literal> на директиву +<literal>fastcgi_pass</literal> и измените параметр на +<literal>localhost:9000</literal>. +В PHP параметр <literal>SCRIPT_FILENAME</literal> используется для +определения имени скрипта, а в параметре <literal>QUERY_STRING</literal> +передаются параметры запроса. +Получится следующая конфигурация: +<programlisting> +server { + location / { + fastcgi_pass localhost:9000; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + fastcgi_param QUERY_STRING $query_string; + } + + location ~ \.(gif|jpg|png)$ { + root /data/images; + } +} +</programlisting> +Таким образом будет настроен сервер, который будет перенаправлять +все запросы, кроме запросов статических изображений, на проксируемый +сервер, работающий по адресу <literal>localhost:9000</literal>, +по протоколу FastCGI. +</para> + +</section> + +</article>
--- a/xml/ru/docs/index.xml +++ b/xml/ru/docs/index.xml @@ -8,7 +8,7 @@ <article name="nginx: документация" link="/ru/docs/" lang="ru" - rev="7" + rev="8" toc="no"> @@ -22,6 +22,10 @@ </listitem> <listitem> +<link doc="beginners_guide.xml"/> +</listitem> + +<listitem> <link doc="control.xml"/> </listitem>