Nginx: Configuration Guide (1)

Source: Internet
Author: User


Beginner ' s Guide

This is guide gives a basic introduction to Nginx and describes some the simple tasks so can do with it. It is supposed that nginx are already installed on the reader ' s machine. If It is not, the installing Nginx page. This is guide describes how to start and stop Nginx, and reload its configuration, explains the structure of the Configuratio n file and describes how to set up Nginx to serve out static content, how to configure Nginx as a proxy server, and 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 worker among. The number of worker processes is defined in the configuration file and may are fixed for a given configuration or Automati Cally adjusted to the number of available CPU cores (in the worker_processes).

The way Nginx and its modules work are determined in the configuration file. By default, the configuration file was named Nginx.conf and placed in the Directory/usr/local/nginx/conf,/etc/nginx, Or/usr/local/etc/nginx.


starting, stopping, and reloading Configuration

To start Nginx, run the executable file. Once Nginx is started, it can being controlled by invoking the executable with The-s. Use the following syntax:

Nginx-s Signal

Where signal May is one of the following:stop-fast shutdown quit-graceful shutdown reload-reloading On file reopen-reopening the log files

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

Nginx-s quit
This command should is executed under the same user that started Nginx.

Changes made in the configuration file won't be applied until the command to reload configuration are sent to Nginx or I T is restarted. To reload configuration, execute:

Nginx-s Reload

Once The master process receives the signal to reload configuration, it checks the syntax of the new validity n 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, Requestin g 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 req Uests until all such requests are serviced. After this, the old worker processes exit.

A signal may also is sent to Nginx processes and the help of Unix tools such as Thekill utility. In this case a signal are sent directly to a process with a given process ID. the process ID of the Nginx master process is written, by default, to Thenginx.pid in the Directory/usr/local/nginx/lo GS Or/var/run. For example, if the master process ID was 1628, to send the QUIT signal resulting in nginx ' s graceful shutdown, execute:

Kill-s QUIT 1628

For getting the "list of all" running nginx processes, theps utility May is used, for example, in the following way:

Ps-ax | grep nginx

For more information on sending signals to Nginx, seecontrolling Nginx.


Configuration File ' s Structure

Nginx consists of modules which are controlled by directives in the specified file. directives are divided into simple directives and block directives. A simple directive consists to 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 Additio NAL instructions surrounded by braces ({and}). If a block directive can have the other directives inside braces, it is called a context (Examples:events,http,server, a D location).

Directives placed in the configuration file outside of the, any contexts are considered the to is in th emain context. The events and HTTP directives reside in the main context,server in HTTP, and location inserver.

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


Serving Static Content

An important Web server task was serving out files (such as images or static HTML pages). You'll implement an example where, depending on the request, the files would be served from different local directories:/data /www (which may contain HTML files) and/data/images (containing images). This would require editing of the configuration file and setting up to a server block inside the HTTP blocks with two Locati On blocks.

A, create the/data/www directory and put a index.html file with no text content into it and create the/data/images D Irectory and place some images in it.

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

HTTP {
    server {
    }
}}

Generally, the configuration file may include Severalserver blocksdistinguished by ports in which they listen to and by SE RVer names. Once Nginx decides which server processes a request, it tests the URI specified in the request ' s header against the PA Rameters of thelocation directives defined inside theserver block.

ADD the following location blocks to theserver blocks:

Location  /{
    root  /data/www;
}

This location blocks specifies the "/" prefix compared with the URI from the request. For matching requests, the URI would be added to the path specified in the root directive, which is, to/data/www, to form T He path to the requested file on the local file system. If There are several matching location blocks Nginx selects the one with the longest. The location block above provides the shortest prefix, of length one, and I if all otherlocation blocks fail to Prov IDE a match, this block would be used.

Next, add the second location block:

location/images/{
    root/data;
}

It is a match for requests starting with/images/(Location/also matches such requests, but has shorter).

The resulting configuration of theserver blocks should look like this:

server {
    location/{
        root/data/www;
    }

    location/images/{
        root/data
    }
}

This is already a working configuration of the a server that listens on the standard port and are accessible on the local MA Chine athttp://localhost/. in response to requests with URIs starting with/images/, the server'll send files from the/data/images directory. For example, in response to Thehttp://localhost/images/example.png request Nginx'll send The/data/images/example.png fi Le. If Such file does not exist, Nginx'll send a response indicating the 404 error. Requests with URIs not starting With/images/will is mapped onto directory. For example, in response to thehttp://localhost/some/example.html request Nginx'll send the/data/www/some/example.html File.

To apply the new configuration, start nginx if it isn't yet started or send thereload signal to the Nginx ' s master proces s, by executing:

Nginx-s Reload
in case something does not work as expected, you may try to find out the reason Inaccess.log anderror.log files in the Directory/usr/local/nginx/logs Or/var/log/nginx.


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 to the them.

We'll configure a basic proxy server, which serves requests of images with files to the local directory and sends all Requests to a proxied server. In this example, both servers is defined on a single nginx instance.

Define the proxied server by adding one more server blocks to the Nginx ' s configuration file with the following cont Ents:

server {
    listen 8080;
    Root/data/up1;

    Location/{
    }
}

This is a simple server that listens on the port 8080 (previously, the Listen directive has does not been specified since T He standard port is used and maps all requests to the/data/up1 directory in the local file system. Create This directory and put the index.html file into it. Note that theroot directive are placed in the theserver context. Suchroot directive is used then the location block selected to serving a request does not include ownroot directive.

Next, use the "Server configuration from" Previous section and modify it to make it a proxy server configuration. In the firstlocation blocks, put the Proxy_pass directive with the protocol, name and port of the proxied server specified In the parameter (we case, it ishttp://localhost:8080):

server {
    location/{
        proxy_pass http://localhost:8080;
    }

    location/images/{
        root/data
    }
}

We'll modify the Secondlocation block, which currently maps requests with The/images/prefix to the files under /images directory, to make it match the requests of images with typical file extensions. The modified location block looks as this:

Location ~ \. (gif|jpg|png) $ {
    root/data/images;
}

The parameter is a regular expression matching all URIs ending with. gif,. jpg, or. png. A regular expression should be preceded with~. The corresponding requests is mapped to the/data/images directory.

When Nginx selects a location blocks to serve a request it I checkslocation directives that specify prefixes Ng location with the longest prefix, and then checks regular. If There is a match with a regular expression, Nginx picks this location or, otherwise, it picks the one remembered Earlie R.

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

server {
    location/{
        proxy_pass http://localhost:8080/;
    }

    Location ~ \. (gif|jpg|png) $ {
        root/data/images;
    }
}

This server'll filter requests ending with. gif,. jpg, or.png and map them to the/data/images directory (by adding U RI to theroot directive ' s parameter) and pass all other requests to the proxied server configured.

To apply new configuration, send thereload signal to Nginx as described in the previous sections.

There are many more directives the May is used to further configure a proxy connection.


Setting up FastCGI proxying

Nginx can is used to route requests to FastCGI servers which run applications built with various frameworks and programmin G languages such as PHP.

The most basic nginx configuration to work with a FastCGI server includes using thefastcgi_pass directive instead of T Heproxy_pass directive, and Fastcgi_param directives to set parameters passed to a fastcgi server. Suppose the FastCGI server is accessible on localhost:9000. Taking the proxy configuration from the previous section as a basis, replace Theproxy_pass directive with the Fastcgi_pass directive and change the parameter to localhost:9000. In PHP, thescript_filename parameter are used for determining the script name, and the query_string parameter are used to PA SS Request parameters. The resulting configuration would is:

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;
    }
}

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


controlling Nginx

Nginx can is controlled with signals. The process ID of the master process is written to the File/usr/local/nginx/logs/nginx.pid by default. This name may is changed at configuration time, or in nginx.conf using thepid directive. The master process supports the following signals:

TERM, INT Fast Shutdown
QUIT Graceful shutdown
HUP Changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes WI Th a new configuration, graceful shutdown of old worker processes
USR1 Re-opening log files
USR2 Upgrading an executable file
Winch Graceful shutdown of worker processes

Individual worker processes can be controlled with signals as very, though it is not required. The supported signals are:

TERM, INT Fast Shutdown
QUIT Graceful shutdown
USR1 Re-opening log files
Winch Abnormal termination for debugging (Requiresdebug_points to is enabled)

changing Configuration

In order for Nginx to re-read the configuration file, a HUP signal should is sent to the master process. The master process checks the syntax validity, then tries to apply new configuration, which is, to open log files and new listen sockets. If This is fails, it rolls back changes and continues to work with the old configuration. If This is succeeds, it starts new worker processes, and sends messages to old worker processes requesting the to them down Gracefully. Old worker processes close listen sockets and continue to service old clients. After all clients are serviced, old worker processes are shut down.

Let ' s illustrate that by example. Imagine that Nginx are run on FreeBSD 4.x and the command

PS Axw-o Pid,ppid,user,%cpu,vsz,wchan,command | Egrep ' (nginx| PID) '

Produces the following output:

   PID   PPID   USER    %cpu   VSZ  wchan  COMMAND
33126          1  root             0.0    1148  Pause        nginx:master process/usr/local/nginx/sbin/nginx
33127  33126 Nobody 0.0    1380  kqread      nginx:worker process (nginx)
33128  33126  nobody 0.0 1364 kqread      Nginx:worker Process (nginx)
33129  33126  Nobody       0.0  1364 kqread nginx      : Worker process (Nginx)

If HUP is sent to the master process, the output becomes:

   PID    PPID   USER    %cpu   VSZ wchan  COMMAND
33126         1    root             0.0  1164  Pause        nginx:master process/usr/local/nginx/sbin/nginx
33129  33126  Nobody         0.0  1380  kqread       nginx:worker process is shutting down (nginx)
33134  33126 nobody 0.0 1368  kqread       nginx:worker process (nginx)
33135  33126 nobody 0.0 Kqread       Nginx:worker Process (nginx)
33136  33126       nobody 0.0 1368 Kqread Nginx:worker process (Nginx)

One of the old worker processes and PID 33129 still continues to work. After some time it exits:

  PID   PPID    USER    %cpu   VSZ wchan  COMMAND
33126         1   root              0.0   1164        Pause Nginx:master process/usr/local/nginx/sbin/nginx
33134  33126   Nobody       0.0   1368 Kqread       Nginx:worker Process (nginx)
33135  33126   Nobody       0.0 1368 Kqread Nginx:worker Process (nginx)
33136  33126   Nobody 0.0 1368 kqread nginx:worker       process (nginx)


Rotating Log-files

In order to rotate log files, they need to is renamed. After that USR1 signal should is sent to the master process. The master process would then re-open all currently open log files and assign them an unprivileged user under which the WOR Ker processes are running, as an owner. After successful re-opening, the master process closes "All open files and sends" to "worker process to" ask them to re-open files. Worker processes also open new files and close old files right away. As a result, the old files are almost immediately available for post processing, such as compression.


upgrading executable on the Fly

    in order to upgrade the server executable, the new executable file should is put in place of the File A. After that USR2 signal should is sent to the master process. the master process renames its file with the process ID to a new file with The.oldbin suffix, e.g./usr/local /nginx/logs/nginx.pid.oldbin, then starts a new executable file T

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.