Install and configure the nginx environment (suitable for beginners)

Source: Internet
Author: User
Tags epoll imap regular expression web services pkill


Nginx overview

Nginx ("engine x") is a high-performance HTTP and reverse proxy server and an IMAP/POP3/SMTP proxy server. Nginx was developed by the Rambler.ru site, where Igor Sysoev is the second highest traffic in Russia. The first public version 0.1.0 was released in October 4, 2004. The source code is released in the form of a BSD-like license. It is well known for its stability, rich feature sets, sample configuration files, and low consumption of system resources. Nginx 1.0.4 was released on July 15, June 1, 2011.

Nginx is a lightweight Web server/reverse proxy server and email (IMAP/POP3) proxy server, which is released under a BSD-like protocol. Developed by Russian programmer Igor Sysoev, Rambler is used by Russia's large entry-level website and search engine Rambler (Russian: Russian. It is characterized by a small amount of memory and high concurrency. In fact, nginx's concurrency is indeed good in the same type of web servers. Users who use nginx websites in mainland China include: sina, Netease, and Tencent.

Common nginx commands

1. Start nginx

If Nginx is installed in the usr/local/nginx/directory, the startup command is:

# Usr/local/nginx/sbin/nginx-c usr/local/nginx/conf/nginx. conf
The-c parameter specifies the configuration file loaded when nginx is started. Of course, you can also choose not to specify the configuration file, omit-c, or start.

# Usr/local/nginx/sbin/nginx
For example, if nginx has been installed in the etc directory in our editing environment, enter nginx at the command prompt to start nginx.

2. Stop nginx

# Nginx-s stop or
# Nginx-s quit or
# Pkill-9 nginx
3. nginx reload configuration

# Nginx-s reload
4. Check whether the configuration file is correct

# Nginx-t

Nginx initial experience

Enter http: // 127.0.0.1/in the address, and then we will see "welcome to nginx ". As shown in the following figure.


The following code is the default configuration of the server segment in the nginx. conf configuration file. All functions implemented by nginx are based on this file. We will continue to explain in the following content.

Server {
Listen 80;
Server_name localhost;
# Charset KOI8-R;
# Access_log logs/host. access. log main;
Location /{
Root/root; # define the default website root directory location of the server
Index. php index.html index.htm; # define the name of the home index file
        }
# Error_page 404/404 .html;
# Redirect server error pages to the static page/50x.html
Error_page 500 502 503 x.html;
Location =/50x.html {
Root html;
        }
}

Next, let's try it in our editing environment. First, start the nginx service and click access test to see what will happen?


Nginx configuration system

The nginx configuration system consists of a master configuration file and other auxiliary configuration files. These configuration files are all plain text files, all in the conf directory under the nginx installation directory.

The line starting with # in the configuration file, or the line ending with a number of spaces or tabs, and then followed by # is considered as a comment, that is, it is only meaningful to the user who edits and views the file, when the program reads these annotation lines, its actual content is ignored.

Because files except the main configuration file nginx. conf are used in some cases, only the main configuration file is used under any circumstances. So here we will take the main configuration file as an example to explain the nginx configuration system.

Nginx. conf contains several configuration items. Each configuration item consists of configuration instructions and command parameters. The command parameter is the configuration value corresponding to the configuration command.

The configuration instruction is a string that can be enclosed in single or double quotation marks or not. However, if the configuration instruction contains spaces, it must be caused.

The command parameters are separated by one or more spaces or TAB characters. The command parameters consist of one or more TOKEN strings. TOKEN strings are separated by spaces or TAB keys.

Configuration File structure
The core modules of Nginx are Main and Events. In addition, they include the standard HTTP Module, optional HTTP module, and mail module. They also support many third-party modules. Main is used to configure parameters related to error logs, processes, and permissions. Events is used to configure IO models, such as epoll, kqueue, select, and poll. They are necessary modules, the HTTP module is used to control the HTTP process of Nginx.

The main configuration file of Nginx consists of several segments, which are also called the nginx context. The definition format of each segment is as follows. Note that each of its commands must end with a semicolon (;); otherwise, it is a syntax error.

<Section> {
<Directive> <parameters>
}
 
The main structure (all configurations end with a semicolon) is as follows:

# Main section, defining global attributes
Events {
# Define the working mechanism under different IO models;
}
Http {
# Define the relevant attributes of the web server (you can also reverse proxy mail)
Server {
# Define the attributes of a vm. All web services must be defined as one VM, which is different from httpd.
Location [option] uri {
# Define the features of a URI
# Nested location
Location [option] uri {
# Nested location
                 }
If (condition ){
# Define URL rewriting
                }
            }
      }
Upstream <Name> {
# Combine multiple servers to achieve load balancing
     }
 }

Configuration instructions

Define user and user group commands for Nginx running.

User www-data;
Defines the number of nginx processes and uses the worker_processes command. We recommend that you set it to equal to the total number of CPU cores.

Worker_processes 8;
The global error log definition type. [debug | info | notice | warn | error | crit] the error_log command is used. In addition, logs can be defined in the http, server, and location contexts, with the same syntax format.

Error_log/var/log/nginx/error. log info;
Define process files using pid commands

Pid/var/run/nginx. pid;
Use the worker_rlimit_nofile command to describe the maximum number of file descriptors opened by the nginx process. We recommend that you set this parameter to the default value.

Worker_rlimit_nofile 65535;

Configuration instructions


Reference event model command: use [kqueue | rtsig | epoll |/dev/poll | select | poll];

Use epoll;
Note: the epoll model is a high-performance network I/O model in Linux 2.6 and later kernel versions. If you are running on FreeBSD, use the kqueue model.

Command used to set the maximum number of connections of a single process: worker_connections (maximum number of connections = number of connections * number of processes)

Worker_connections 65535;

Configuration instructions

Sets the mime type. The type is defined by the mime. type file using the include command.

Include/etc/nginx/mime. types;
Default_type application/octet-stream;
Enable gzip compression commands

Gzip on;
Gzip_disable "MSIE [1-6] \. (?!. * SV1 )";
Set the command upstream for the server list of server load balancer.

Upstream mysvr {
# The weigth parameter indicates the weight. A higher weight indicates a higher probability of being assigned.
# Enable port 3128 for Squid on the local machine
Server 192.168.8.1: 3128 weight = 5;
Server 192.168.8.2: 80 weight = 1;
Server 192.168.8.3: 80 weight = 6;
    }
Sets the VM command server, including the port, host name, and default request.

Server {
# Listening to port 80
Listen 80;
# Define access using www.xx.com
Server_name www.xx.com;
# Set access logs for the current virtual host
Access_log logs/www.xx.com. access. log main;
# Default request
Location /{
Root/root; # define the default website root directory location of the server
Index. php index.html index.htm; # define the name of the home index file
Fastcgi_pass www.xx.com;
Fastcgi_param SCRIPT_FILENAME $ document_root/$ fastcgi_script_name;
Include/etc/nginx/fastcgi_params;
        }
 
# Define error prompt page
Error_page 500 502 503 x.html;
Location =/50x.html {
Root/root;
    }
}

Request direction command proxy_pass

Proxy_pass http://www.111cn.net;


Server load balancer

Load balancing (also known as Load balancing) is called Load Balance, which means to Balance the Load (work task) and distribute it to multiple operation units for execution, for example, the Web server, FTP server, enterprise key application server, and other key task servers can work together to complete tasks.

Currently, nginx upstream supports four allocation methods.

1) Round Robin (default) each request is distributed to different backend servers one by one in chronological order. If the backend servers are down, they can be automatically removed.

2) weight specifies the polling probability. weight is directly proportional to the access ratio, which is used when the backend server performance is uneven.

3) ip_hash: each request is allocated according to the hash result of the access ip address, so that each visitor accesses a backend server at a fixed time, which can solve the session problem.

4) fair (a third party) allocates requests based on the response time of the backend server. Requests with short response time are prioritized.

Upstream ixdba.net {
Ip_hash;
Server 192.168.12.133: 80;
Server 192.168.12.134: 80 down;
Server 192.168.12.135: 8009 max_fails = 3 fail_timeout = 20 s;
Server 192.168.12.136: 8080;
}
Upstream is the HTTP Upstream module of Nginx. This module uses a simple scheduling algorithm to achieve load balancing between client IP addresses and backend servers. In the preceding settings, the name of a server load balancer is specified using the upstream command ixdba.net. This name can be specified at will and can be called directly as needed.


Location configuration

Syntax rule: location [= | ~ | ~ * | ^ ~] /Uri /{... }

Wildcard description
= Indicates exact match.
^ ~ It indicates that the uri starts with a regular string and is understood as a matching url path.
~ It indicates a case-sensitive regular match.
!~ Case-insensitive
!~ * Case-insensitive mismatch
~ * Indicates case-insensitive regular matching.
/Universal match, any request will match
First match =, second match ^ ~, Second, regular matching based on the order in the file, and finally handing over to/Universal matching. When a match is successful, stop the match and process the request according to the current matching rule.

Location = /{
# Rule
}
Location =/login {
# Rule B
}
Location ^ ~ /Static /{
# Rule C
}
Location ~ \. (Gif | jpg | png | js | css) $ {
# Rule D
}
The result is as follows:

Access the root directory/, for example, http: // localhost/will match rule;
Access http: // localhost/login will match rule B;
Access http: // localhost/static/a.html will match rule C;
Access http: // localhost/a.gif, http: // localhost/B .jpg will match rule D.


Rewrite rules

Commands related to Nginx Rewrite rules include if, rewrite, set, return, and break. The most important of these commands is rewrite. A simple Nginx Rewrite rule syntax is as follows:

Rewrite ^/B/(. *) \. html/play. php? Video = $1 break;
Regular Expression Matching, where:

1 .~ It is case-sensitive;
2 .~ * Is case-insensitive;
3 .!~ And !~ * Case-insensitive and case-insensitive.
File and directory match, where:

1.-f and! -F is used to determine whether a file exists;
2.-d and! -D is used to determine whether a directory exists;
3.-e and! -E is used to determine whether a file or directory exists;
4.-x and! -X is used to determine whether a file is executable.
Flag labels include:

1. last is equivalent to the [L] Mark in Apache, indicating that rewrite is completed;
2. The break terminates the match and does not match the subsequent rules;
3. If redirect returns 302, the address bar of the temporary redirection will display the address after the jump;
4. When permanent returns 301, the address bar of the permanent redirection will display the address after the jump.
Of course, in addition to these, some corresponding global variables will be used in the Rewrite rules, such as $ args and $ ur.


Write your own nginx configuration file

In the previous sections, we have learned the configuration instructions for each segment in the nginx configuration file. Next we will write a configuration file of our own. The following code:

Worker_processes 1;
Events {
Worker_connections 1024;
}
Http {
Server {
Location /{
# Root html; # define the default website root directory location of the server
# Index. php index.html index.htm; # define the name of the home index file
Proxy_pass http://www.111cn.net;
        }
Error_page 500 502 503 x.html;
Location =/50x.html {
Root html;
       }
   }
}
In this way, our configuration file is complete. Stop the nginx service first, and then use nginx-c *. conf command to restart nginx ,*. conf is the path of our configuration file. After nginx is started, enter the corresponding address in the address bar to see what happens and whether it has been forwarded to the site we configured.

For example, you can edit a configuration file on the editing page on the right. The configuration file name is Mynginx. conf, the content of which is the above content, saved in the/etc/nginx Directory, after completing the following operations:

Pkill-9 nginx/* stop nginx service */
Nginx-c/etc/nginx/Mynginx. conf/* load your configuration file */


Reverse proxy example

A Reverse Proxy is a Proxy server that receives connection requests from the Internet and forwards the requests to servers on the internal network, the result obtained from the server is returned to the client requesting connection from the Internet.

For example, you need to configure the ip address and port used by the backend to run the apache service. That is to say, our goal is to access your website through http: // ip: port. You can modify the configuration file to the following content and reload nginx.

# Basic reverse proxy server ##
Upstream apachephp {
Server ip: 8080; # Apache
 }
# Start www.nowamagic.net ##
Server {
Listen 80;
Server_name www.nowamagic.net;
Access_log logs/quancha. access. log main;
Error_log logs/quancha. error. log;
Root html;
Index index.html index.htm index. php;
  
# Send request back to apache ##
Location /{
Proxy_pass http: // apachephp;
#........................
}
}


Virtual host example
Nginx is used as a virtual host, especially for pure static-html. This is the simplest application. It can be understood as the simplest Web server that only supports static pages.

In this example, the configuration of two virtual hosts (pure static-html support) is supported. We only need to modify the server segment, as shown below:

Server {
Listen 80;
Server_name www.111cn.net;
# Charset KOI8-R;
# Access_log logs/host. access. log main;
Location /{
Root/root;
Index. php index.html index.htm;
                   
        }
Error_page 500 502 503 x.html;
Location =/50x.html {
Root html;
        }
      }
Server {
Listen 80;
Server_name www.baidu.com;
# Charset KOI8-R;
# Access_log logs/host. access. log main;
Location /{
Root/root;
Index. php index.html index.htm;
                    
        }
Error_page 500 502 503 x.html;
Location =/50x.html {
Root html;
        }
}

Forward proxy example
The nginx forward proxy configuration is as follows:

Server
{
Listen 8080;
Server_name www.jbxue.com;
Index index.html index.htm index. php;
Root/home/wwwroot;
Location /{
Resolver 192.168.8.88;
Proxy_pass $ scheme: // $ http_host $ request_uri;
Proxy_buffers 256 4 k;
 }
Access_log off;
}

Note:

1. No hostname is allowed.

2. There must be a resolver, that is, dns, that is, the above x. x. x. x, replace it with the DNS server ip address of the current machine (view dns method cat/etc/resolv. conf proxy ).

3. $ http_host and $ request_uri are nginx system variables, which must be unchanged.

After checking that the configuration file is correct, restart nginx and add the IP address of the proxy server in the browser to use the Nginx forward proxy.


Server load balancer example
Upstream backend {
# Define the Ip address and device status of the server load balancer device
Server 127.0.0.1: 9090 down;
Server 192.168.1.12: 8080 weight = 2;
Server 192.168.1.13: 6060 max_fails = 3 fail_timeout = 30 s;
Server 1193851.14: 7070 backup;
}
Server {
#..............................
Location /{
Proxy_pass http: // backend;
#..............................
    }
}
The above code is an example of a server load balancer application.

Upstream can perform health check on backend servers.

A) down indicates that the current server is not involved in the load.

B) the default weight value is 1. The larger the weight value, the larger the load weight.

C) max_fails: number of failed requests to the backend server within the fail_timeout time.

D) fail_timeout: the pause time after max_fails fails.

E) backup: requests the backup machine when all other non-backup machines are down or busy. Therefore, this machine is under the least pressure.

Continue learning


Rewrite Simple example
Worker_processes 1;
Events {
Worker_connections 1024;
}
Http {
Server {
Location/hubwiz {
Rewrite (. *) http://www.111cn.net;
        }
Location/baidu {
Rewrite (. *) http://www.baidu.com;
        }
Error_page 500 502 503 x.html;
Location =/50x.html {
Root html;
       }
   }
}

Modify our own configuration file, save, reload nginx, and click access test according to the content and code above ], enter "/hubwiz" and "/baidu" respectively after the address given in the address bar. Will the result be the same as mine?

Enter "/hubwiz" to go to Huizhi network, and enter "/baidu" to go to baidu?

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.