How to configure nginx

How to configure nginx

How to configure nginx. Смотреть фото How to configure nginx. Смотреть картинку How to configure nginx. Картинка про How to configure nginx. Фото How to configure nginx

Beginner’s Guide

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 Installing nginx 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.

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 worker_processes).

Starting, Stopping, and Reloading Configuration

Where signal may be one of the following:

For example, to stop nginx processes with waiting for the worker processes to finish serving current requests, the following command can be executed:

This command should be executed under the same user that started nginx.

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:

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.

For getting the list of all running nginx processes, the ps utility may be used, for example, in the following way:

For more information on sending signals to nginx, see Controlling nginx.

Configuration File’s Structure

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 ( ; ). 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 ( < and >). If a block directive can have other directives inside braces, it is called a context (examples: events, http, server, and location).

The rest of a line after the # sign is considered a comment.

Serving Static Content

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: /data/www (which may contain HTML files) and /data/images (containing images). This will require editing of the configuration file and setting up of a server block inside the http block with two location blocks.

First, create the /data/www directory and put an index.html file with any text content into it and create the /data/images directory and place some images in it.

Next, open the configuration file. The default configuration file already includes several examples of the server block, mostly commented out. For now comment out all such blocks and start a new server block:

Generally, the configuration file may include several server blocks distinguished by ports on which they listen to and by server names. Once nginx decides which server processes a request, it tests the URI specified in the request’s header against the parameters of the location directives defined inside the server block.

Add the following location block to the server block:

Next, add the second location block:

It will be a match for requests starting with /images/ ( location / also matches such requests, but has shorter prefix).

The resulting configuration of the server block should look like this:

To apply the new configuration, start nginx if it is not yet started or send the reload signal to the nginx’s master process, by executing:

Setting Up a Simple Proxy Server

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.

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.

First, define the proxied server by adding one more server block to the nginx’s configuration file with the following contents:

This will be a simple server that listens on the port 8080 (previously, the listen directive has not been specified since the standard port 80 was used) and maps all requests to the /data/up1 directory on the local file system. Create this directory and put the index.html file into it. Note that the root directive is placed in the server context. Such root directive is used when the location block selected for serving a request does not include its own root directive.

Next, use the server configuration from the previous section and modify it to make it a proxy server configuration. In the first location block, put the proxy_pass directive with the protocol, name and port of the proxied server specified in the parameter (in our case, it is http://localhost:8080 ):

We will modify the second location block, which currently maps requests with the /images/ prefix to the files under the /data/images directory, to make it match the requests of images with typical file extensions. The modified location block looks like this:

. The corresponding requests will be mapped to the /data/images directory.

When nginx selects a location block to serve a request it first checks location directives that specify prefixes, remembering location with the longest prefix, and then checks regular expressions. If there is a match with a regular expression, nginx picks this location or, otherwise, it picks the one remembered earlier.

The resulting configuration of a proxy server will look like this:

To apply new configuration, send the reload signal to nginx as described in the previous sections.

There are many more directives that may be used to further configure a proxy connection.

Setting Up FastCGI Proxying

nginx can be used to route requests to FastCGI servers which run applications built with various frameworks and programming languages such as PHP.

This will set up a server that will route all requests except for requests for static images to the proxied server operating on localhost:9000 through the FastCGI protocol.

How to configure nginx. Смотреть фото How to configure nginx. Смотреть картинку How to configure nginx. Картинка про How to configure nginx. Фото How to configure nginx

Руководство для начинающих

В этом руководстве даётся начальное введение в nginx и описываются некоторые простые задачи, которые могут быть решены с его помощью. Предполагается, что nginx уже установлен на компьютере читателя. Если нет, см. Установка nginx. В этом руководстве описывается, как запустить и остановить nginx и перезагрузить его конфигурацию, объясняется, как устроен конфигурационный файл, и описывается, как настроить nginx для раздачи статического содержимого, как настроить прокси-сервер на nginx, и как связать nginx с приложением FastCGI.

У nginx есть один главный и несколько рабочих процессов. Основная задача главного процесса — чтение и проверка конфигурации и управление рабочими процессами. Рабочие процессы выполняют фактическую обработку запросов. nginx использует модель, основанную на событиях, и зависящие от операционной системы механизмы для эффективного распределения запросов между рабочими процессами. Количество рабочих процессов задаётся в конфигурационном файле и может быть фиксированным для данной конфигурации или автоматически устанавливаться равным числу доступных процессорных ядер (см. worker_processes).

Запуск, остановка, перезагрузка конфигурации

Где сигнал может быть одним из нижеследующих:

Например, чтобы остановить процессы nginx с ожиданием окончания обслуживания текущих запросов рабочими процессами, можно выполнить следующую команду:

Команда должна быть выполнена под тем же пользователем, под которым был запущен nginx.

Изменения, сделанные в конфигурационном файле, не будут применены, пока команда перезагрузить конфигурацию не будет вручную отправлена nginx’у или он не будет перезапущен. Для перезагрузки конфигурации выполните:

Получив сигнал, главный процесс проверяет правильность синтаксиса нового конфигурационного файла и пытается применить конфигурацию, содержащуюся в нём. Если это ему удаётся, главный процесс запускает новые рабочие процессы и отправляет сообщения старым рабочим процессам с требованием завершиться. В противном случае, главный процесс откатывает изменения и продолжает работать со старой конфигурацией. Старые рабочие процессы, получив команду завершиться, прекращают принимать новые запросы и продолжают обслуживать текущие запросы до тех пор, пока все такие запросы не будут обслужены. После этого старые рабочие процессы завершаются.

Дополнительную информацию об отправке сигналов процессам nginx можно найти в Управление nginx.

Структура конфигурационного файла

nginx состоит из модулей, которые настраиваются директивами, указанными в конфигурационном файле. Директивы делятся на простые и блочные. Простая директива состоит из имени и параметров, разделённых пробелами, и оканчивается точкой с запятой ( ; ). Блочная директива устроена так же, как и простая директива, но вместо точки с запятой после имени и параметров следует набор дополнительных инструкций, помещённых внутри фигурных скобок ( < и >). Если у блочной директивы внутри фигурных скобок можно задавать другие директивы, то она называется контекстом (примеры: events, http, server и location).

Часть строки после символа # считается комментарием.

Раздача статического содержимого

Во-первых, создайте каталог /data/www и положите в него файл index.html с любым текстовым содержанием, а также создайте каталог /data/images и положите в него несколько файлов с изображениями.

В блок server добавьте блок location следующего вида:

Далее, добавьте второй блок location :

Он будет давать совпадение с запросами, начинающимися с /images/ ( location / для них тоже подходит, но указанный там префикс короче).

Итоговая конфигурация блока server должна выглядеть следующим образом:

Чтобы применить новую конфигурацию, запустите nginx, если он ещё не запущен, или отправьте сигнал reload главному процессу nginx, выполнив:

Настройка простого прокси-сервера

Одним из частых применений nginx является использование его в качестве прокси-сервера, то есть сервера, который принимает запросы, перенаправляет их на проксируемые сервера, получает ответы от них и отправляет их клиенту.

Мы настроим базовый прокси-сервер, который будет обслуживать запросы изображений из локального каталога и отправлять все остальные запросы на проксируемый сервер. В этом примере оба сервера будут работать в рамках одного экземпляра nginx.

Во-первых, создайте проксируемый сервер, добавив ещё один блок server в конфигурационный файл nginx со следующим содержимым:

Далее, используйте конфигурацию сервера из предыдущего раздела и видоизмените её, превратив в конфигурацию прокси-сервера. В первый блок location добавьте директиву proxy_pass, указав протокол, имя и порт проксируемого сервера в качестве параметра (в нашем случае это http://localhost:8080 ):

Итоговая конфигурация прокси-сервера выглядит следующим образом:

Чтобы применить новую конфигурацию, отправьте сигнал reload nginx’у, как описывалось в предыдущих разделах.

Существует множество других директив для дальнейшей настройки прокси-соединения.

Настройка проксирования FastCGI

nginx можно использовать для перенаправления запросов на FastCGI-серверы. На них могут исполняться приложения, созданные с использованием разнообразных фреймворков и языков программирования, например, PHP.

How to configure nginx

Your submission was sent successfully! Close

1. Overview

Nginx (pronounced as “Engine-X”) is an open source web server that is often used as reverse proxy or HTTP cache. It is available for Linux for free.

In this tutorial we’ll install Nginx and set up a basic site.

What you’ll learn

What you’ll need

Originally authored by Marcin Mikołajczak

2. Installing Nginx

To install Nginx, use following command:

After installing it, you already have everything you need.

You can point your browser to your server IP address. You should see this page:

How to configure nginx. Смотреть фото How to configure nginx. Смотреть картинку How to configure nginx. Картинка про How to configure nginx. Фото How to configure nginx

If you see this page, you have successfully installed Nginx on your web server.

3. Creating our own website

Default page is placed in /var/www/html/ location. You can place your static pages here, or use virtual host and place it other location.

Virtual host is a method of hosting multiple domain names on the same server.

Let’s create simple HTML page in /var/www/tutorial/ (it can be anything you want). Create index.html file in this location.

Paste the following to the index.html file:

Save this file. In next step we are going to set up virtual host to make Nginx use pages from this location.

4. Setting up virtual host

To set up virtual host, we need to create file in /etc/nginx/sites-enabled/ directory.

For this tutorial, we will make our site available on 81 port, not the standard 80 port. You can change it if you would like to.

5. Activating virtual host and testing results

To make our site working, simply restart Nginx service.

Let’s check if everything works as it should. Open our newly created site in web browser. Remember that we used :81 port.

How to configure nginx. Смотреть фото How to configure nginx. Смотреть картинку How to configure nginx. Картинка про How to configure nginx. Фото How to configure nginx

Congratulations! Everything works as it should. We have just configured Nginx web server.

6. That’s all!

I hope that this tutorial explained you the basics of working with Nginx. Of course, it’s much more powerful tool. You can find more in official resources, available on Nginx site.

If you need more guidance on using Nginx, help is always at hand:

Search Results

No Results

Filters

How to Configure NGINX

How to configure nginx. Смотреть фото How to configure nginx. Смотреть картинку How to configure nginx. Картинка про How to configure nginx. Фото How to configure nginx How to configure nginx. Смотреть фото How to configure nginx. Смотреть картинку How to configure nginx. Картинка про How to configure nginx. Фото How to configure nginx

How to configure nginx. Смотреть фото How to configure nginx. Смотреть картинку How to configure nginx. Картинка про How to configure nginx. Фото How to configure nginx

NGINX is a lightweight, high-performance web server designed for high-traffic use cases. The most common use cases are HTTP cache at scale, load balancing, and reverse proxy.

What makes NGINX stand apart is its capability to serve static content such as HTML and Media files effectively. It uses an event-driven model to provide predictable performance even when the load is high.

This guide shows you several different NGINX server configurations.

NGINX Config: Directives, Blocks, and Contexts

The way NGINX configurations are setup is by:

Note that any character after # in a line becomes a comment. And NGINX does not interpret it.

To better understand directives and blocks, take a look at the condensed copy of /etc/nginx/nginx conf below:

There are 4 directives in this snippet in the main context :

Additional directives can be placed inside of events<…>, http <…>and so on. To read more about directives, visit the official NGINX documentation.

Let’s take a look at these blocks and their NGINX configurations.

http blocks contain directives for handling web traffic. These directives are often universal as they are passed on to all website configurations NGINX serves. A list of available directives for http blocks are available on official NGINX http block documentation.

In the http block there’s an include directive that tells NGINX where website configuration files are located. It changes depending upon your source of NGINX installation:

Regardless of the installation source, server configuration files contain a server block for a website. Here’s an example server block:

There are several directives in this block that are worth taking a look at:

Here are some examples for server_name NGINX configuration based on sites you want to host on the server.

Configuration for processing requests for both example.com and www.example.com :

Configuration for processing requests for all subdomains for example.com :

Configuration for processing requests of all domains that start with example. :

NGINX Configuration of Location Blocks

Location directives cover requests for specific files and folders. It also allows NGINX to respond to requests for resources within the server. Here’s an NGINX location blocks configuration:

Configuring NGINX location directive using regex match

When a location directive is followed by a tilde (

), NGINX server performs a regular expression (regex) match. NGINX uses Perl Compatible Regular Expression (PCRE) for regex. Here’s an example:

If you want this match to be case-insensitive, configure your location directive by adding an asterisk to tilde(

Adding a caret and tilde(^!) to location directives tells NGINX if it matches a particular string stop searching for more specific matches. And to use the directives here instead.

Finally, if you add an equals sign (=), this forces an exact match with the path requested and stops searching for more specific matches.

Location Root and Index Configuration

root and index determine the content of the associated location directive block. Here’s an example:

Here’s a complex example that shows a set of location directives for a server responding to the domain example.com :

Let’s analyze how NGINX handles some requests based on this configuration:

NGINX Configuration of Reverse Proxy

To get started with configuring a reverse proxy, follow these steps.

If not already installed, install NGINX by

This installs NGINX web server.

Deactivate your virtual host. To deactivate your virtual host run

Change your directory to /sites-available and create a reverse proxy there:

Configure proxy server to redirect all requests on port 80 to a lightweight http server that listens to port 8000. To do that, write the following Nginx configuration:

Use the symbolic link and copy configuration from /etc/nginx/sites-available to /etc/nginx/sites-enabled :

Verify if NGINX is working:

If you see a successful test message, NGINX reverse proxy is properly configured on your system.

Configuring Load Balance with NGINX

We assume that you already have NGINX installed. If not, follow the steps from the previous section. To configure your NGINX and use it as a load balancer, add your backend servers to your configuration file first. Collect your server IPs that acts as load balancers:

Every time a request is made to port 80 to SUBDOMAIN.DOMAIN.LTD, request is routed to upstream servers.

After done, execute this new configuration by reloading NGINX using

You can further configure and optimize your load balancer by load balancing methods like Round Robin, Least connected, IP hash, and Weighted.

This page was originally published on Monday, January 18, 2010.

Configuring NGINX and NGINX Plus as a Web Server

Configure NGINX and NGINX Plus as a web server, with support for virtual server multi-tenancy, URI and response rewriting, variables, and error handling.

This article explains how to configure NGINX Open Source and NGINX Plus as a web server, and includes the following sections:

For additional information on how to tune NGINX Plus and NGINX Open Source, watch our free webinar on-demand Installing and Tuning NGINX.

Note: The information in this article applies to both NGINX Open Source and NGINX Plus. For ease of reading, the remainder of the article refers to NGINX Plus only.

At a high level, configuring NGINX Plus as a web server is a matter of defining which URLs it handles and how it processes HTTP requests for resources at those URLs. At a lower level, the configuration defines a set of virtual servers that control the processing of requests for particular domains or IP addresses. For more information about configuration files, see Creating NGINX Plus Configuration Files.

Each virtual server for HTTP traffic defines special configuration instances called locations that control processing of specific sets of URIs. Each location defines its own scenario of what happens to requests that are mapped to this location. NGINX Plus provides full control over this process. Each location can proxy the request or return a file. In addition, the URI can be modified, so that the request is redirected to another location or virtual server. Also, a specific error code can be returned and you can configure a specific page to correspond to each error code.

Setting Up Virtual Servers

The NGINX Plus configuration file must include at least one server directive to define a virtual server. When NGINX Plus processes a request, it first selects the virtual server that will serve the request.

A virtual server is defined by a server directive in the http context, for example:

It is possible to add multiple server directives into the http context to define multiple virtual servers.

The server configuration block usually includes a listen directive to specify the IP address and port (or Unix domain socket and path) on which the server listens for requests. Both IPv4 and IPv6 addresses are accepted; enclose IPv6 addresses in square brackets.

The example below shows configuration of a server that listens on IP address 127.0.0.1 and port 8080:

If there are several servers that match the IP address and port of the request, NGINX Plus tests the request’s Host header field against the server_name directives in the server blocks. The parameter to server_name can be a full (exact) name, a wildcard, or a regular expression. A wildcard is a character string that includes the asterisk ( * ) at its beginning, end, or both; the asterisk matches any sequence of characters. NGINX Plus uses the Perl syntax for regular expressions; precede them with the tilde (

). This example illustrates an exact name.

If several names match the Host header, NGINX Plus selects one by searching for names in the following order and using the first match it finds:

If the Host header field does not match a server name, NGINX Plus routes the request to the default server for the port on which the request arrived. The default server is the first one listed in the nginx.conf file, unless you include the default_server parameter to the listen directive to explicitly designate a server as the default.

Configuring Locations

NGINX Plus can send traffic to different proxies or serve different files based on the request URIs. These blocks are defined using the location directive placed within a server directive.

For example, you can define three location blocks to instruct the virtual server to send some requests to one proxied server, send other requests to a different proxied server, and serve the rest of the requests by delivering files from the local file system.

NGINX Plus tests request URIs against the parameters of all location directives and applies the directives defined in the matching location. Inside each location block, it is usually possible (with a few exceptions) to place even more location directives to further refine the processing for specific groups of requests.

Note: In this guide, the word location refers to a single location context.

There are two types of parameter to the location directive: prefix strings (pathnames) and regular expressions. For a request URI to match a prefix string, it must start with the prefix string.

A regular expression is preceded with the tilde (

) for case-sensitive matching, or the tilde-asterisk (

* ) for case-insensitive matching. The following example matches URIs that include the string .html or .htm in any position.

NGINX Location Priority

To find the location that best matches a URI, NGINX Plus first compares the URI to the locations with a prefix string. It then searches the locations with a regular expression.

Higher priority is given to regular expressions, unless the ^

modifier is used. Among the prefix strings NGINX Plus selects the most specific one (that is, the longest and most complete string). The exact logic for selecting a location to process a request is given below:

A typical use case for the = modifier is requests for / (forward slash). If requests for / are frequent, specifying = / as the parameter to the location directive speeds up processing, because the search for matches stops after the first comparison.

A location context can contain directives that define how to resolve a request – either serve a static file or pass the request to a proxied server. In the following example, requests that match the first location context are served files from the /data directory and the requests that match the second are passed to the proxied server that hosts content for the www.example.com domain.

The proxy_pass directive passes the request to the proxied server accessed with the configured URL. The response from the proxied server is then passed back to the client. In the example above, all requests with URIs that do not start with /images/ are be passed to the proxied server.

Using Variables

Returning Specific Status Codes

Some website URIs require immediate return of a response with a specific error or redirect code, for example when a page has been moved temporarily or permanently. The easiest way to do this is to use the return directive. For example:

The return directive can be included in both the location and server contexts.

Rewriting URIs in Requests

A request URI can be modified multiple times during request processing through the use of the rewrite directive, which has one optional and two required parameters. The first (required) parameter is the regular expression that the request URI must match. The second parameter is the URI to substitute for the matching URI. The optional third parameter is a flag that can halt processing of further rewrite directives or send a redirect (code 301 or 302 ). For example:

As this example shows, the second parameter users captures though matching of regular expressions.

You can include multiple rewrite directives in both the server and location contexts. NGINX Plus executes the directives one-by-one in the order they occur. The rewrite directives in a server context are executed once when that context is selected.

After NGINX processes a set of rewriting instructions, it selects a location context according to the new URI. If the selected location contains rewrite directives, they are executed in turn. If the URI matches any of those, a search for the new location starts after all defined rewrite directives are processed.

The following example shows rewrite directives in combination with a return directive.

There are two parameters that interrupt processing of rewrite directives:

Rewriting HTTP Responses

Sometimes you need to rewrite or change the content in an HTTP response, substituting one string for another. You can use the sub_filter directive to define the rewrite to apply. The directive supports variables and chains of substitutions, making more complex changes possible.

For example, you can change absolute links that refer to a server other than the proxy:

Another example changes the scheme from http:// to https:// and replaces the localhost address with the hostname from the request header field. The sub_filter_once directive tells NGINX to apply sub_filter directives consecutively within a location:

Note that the part of the response already modified with the sub_filter is not replaced again if another sub_filter match occurs.

Handling Errors

With the error_page directive, you can configure NGINX Plus to return a custom page along with an error code, substitute a different error code in the response, or redirect the browser to a different URI. In the following example, the error_page directive specifies the page (/404.html) to return with the 404 error code.

Note that this directive does not mean that the error is returned immediately (the return directive does that), but simply specifies how to treat errors when they occur. The error code can come from a proxied server or occur during processing by NGINX Plus (for example, the 404 results when NGINX Plus can’t find the file requested by the client).

The following configuration is an example of passing a request to the back end when a file is not found. Because there is no status code specified after the equals sign in the error_page directive, the response to the client has the status code returned by the proxied server (not necessarily 404 ).

For example, if /images/some/file is not found, it is replaced with /fetch/images/some/file and a new search for a location starts. As a result, the request ends up in the second location context and is proxied to http://backend/.

The open_file_cache_errors directive prevents writing an error message if a file is not found. This is not necessary here since missing files are correctly handled.

Источники информации:

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

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