: This article mainly introduces Nginx: Beginner's sGuide. For more information about PHP tutorials, see. 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 (seeworker_processes ).
The way nginx and its modules work is determined in the configuration file. By default, the configuration file is namednginx.confAnd 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 be controlled by invoking the executable with-sParameter. Use the following syntax:
nginx -s signal
WhereSignalMay be one of the following:
stop-Fast shutdown
quit-Graceful shutdown
reload-Reloading the configuration file
reopen-Reopening the log files
For example, to stop nginx processes with waiting for the worker processes to finish serving current requests, the following command can be executed:
nginx -s quit
This command shoshould 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:
nginx -s reload
Once the master process has es 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, logging 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.
A signal may also be sent to nginx processes with the help of Unix tools such askillUtility. 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, tonginx.pidIn the directory/usr/local/nginx/logsOr/var/run. For example, if the master process ID is 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,psUtility may be used, for example, in the following way:
ps -ax | grep nginx
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 pided 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 ).
Directives placed in the configuration file outside of any contexts are considered to be in the main context.eventsAndhttpDirectives reside inmainContext,serverInhttp, AndlocationInserver.
The rest of a line after#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/data/wwwDirectory and putindex.htmlFile with any text content into it and create/data/imagesDirectory and place some images in it.
Next, open the configuration file. The default configuration file already includes several examples ofserverBlock, mostly commented out. For now comment out all such blocks and start a newserverBlock:
http { server { }}
Generally, the configuration file may include severalserverBlocks distinguished by ports on which they listento and by server names. Once nginx decides whichserverProcesses a request, it tests the URI specified in the request's header against the parameters oflocationDirectives defined insideserverBlock.
Add the followinglocationBlock toserverBlock:
location / { root /data/www;}
ThislocationBlock specifies the"/"Prefix compared with the URI from the request. For matching requests, the URI will be added to the path specified in the root directive, that is,/data/www, To form the path to the requested file on the local file system. If there are several matchinglocationBlocks nginx selects the one with the longest prefix.locationBlock above provides the shortest prefix, of length one, and so only if all otherlocationBlocks fail to provide a match, this block will be used.
Next, add the secondlocationBlock:
location /images/ { root /data;}
It will be a match for requests starting/images/(location /Also matches such requests, but has shorter prefix ).
The resulting configuration ofserverBlock shoshould look like this:
server { location / { root /data/www; } location /images/ { root /data; }}
This is already a working configuration of a server that listens on the standard port 80 and is accessible on the local machinehttp://localhost/. In response to requests with URIs starting/images/, The server will send files from/data/imagesDirectory. For example, in response tohttp://localhost/images/example.pngRequest nginx will send/data/images/example.pngFile. If such file does not exist, nginx will send a response indicating the 404 error. Requests with URIs not starting/images/Will be mapped onto/data/wwwDirectory. For example, in response tohttp://localhost/some/example.htmlRequest nginx will send/data/www/some/example.htmlFile.
To apply the new configuration, start nginx if it is not yet started or sendreloadSignal to the nginx's master process, by executing:
nginx -s reload
In case something does not work as expected, you may try to find out the reason in
access.logAnd
error.logFiles in the directory
/usr/local/nginx/logsOr
/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 has es 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 moreserverBlock to the nginx's configuration file with the following contents:
server { listen 8080; root /data/up1; location / { }}
This will be a simple server that listens on the port 8080 (previously,listenDirective has not been specified since the standard port 80 was used) and maps all requests to/data/up1Directory on the local file system. Create this directory and putindex.htmlFile into it. Note thatrootDirective is placed inserverContext. SuchrootDirective is used whenlocationBlock selected for serving a request does not include ownrootDirective.
Next, use the server configuration from the previous section and modify it to make it a proxy server configuration. In the firstlocationBlock, put the proxy_pass directive with the protocol, name and port of the proxied server specified in the parameter (in our case, it ishttp://localhost:8080):
server { location / { proxy_pass http://localhost:8080; } location /images/ { root /data; }}
We will modify the secondlocationBlock, which currently maps requests with/images/Prefix to the files under/data/imagesDirectory, to make it match the requests of images with typical file extensions. The modifiedlocationBlock looks like this:
location ~ \.(gif|jpg|png)$ { root /data/images;}
The parameter is a regular expression matching all URIs ending.gif,.jpg, Or.png. A regular expression shocould be preceded~. The corresponding requests will be mapped to/data/imagesDirectory.
When nginx selectslocationBlock to serve a request it first checks location directives that specify prefixes, rememberinglocationWith the longest prefix, and then checks regular expressions. If there is a match with a regular expression, nginx picks thislocationOr, otherwise, it picks the one remembered earlier.
The resulting configuration of a proxy server will look like this:
server { location / { proxy_pass http://localhost:8080/; } location ~ \.(gif|jpg|png)$ { root /data/images; }}
This server will filter requests ending.gif,.jpg, Or.pngAnd map them to/data/imagesDirectory (by adding URI torootDirective's parameter) and pass all other requests to the proxied server configured above.
To apply new configuration, sendreloadSignal to nginx as described in the previous sections.
There are 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 varous frameworks and programming ages such as PHP.
The most basic nginx configuration to work with a FastCGI server has DES using the fastcgi_pass direve VE instead ofproxy_passDirective, and fastcgi_param directives to set parameters passed to a FastCGI server. Suppose the FastCGI server is accessible onlocalhost:9000. Taking the proxy configuration from the previous section as a basis, replaceproxy_passDirective withfastcgi_passDirective and change the parameterlocalhost:9000. In PHP,SCRIPT_FILENAMEParameter is used for determining the script name, andQUERY_STRINGParameter is used to pass request parameters. The resulting configuration wocould be:
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 will set up a server that will route all requests starting t for requests for static images to the proxied server operating onlocalhost:9000Through the FastCGI protocol.
The Nginx: Beginner's Guide is introduced above, including some content. I hope to help anyone who is interested in PHP tutorials.