Nginx installation and configuration file nginxconf detailed

Source: Internet
Author: User
Tags epoll sendfile
1. Installing Nginx

Before installing Nginx, make sure the system has the GCC, openssl-devel, pcre-devel, and Zlib-devel repositories installed.
Here is the Nginx installation process:

wget Http://nginx.org/download/nginx-1.0.14.tar.gztar zxvf nginx-1.0.14.tar.gz./configure--with-http_stub_status_ Module--prefix=/opt/nginxcd nginx-1.0.14makemake Install

The –with-http_stub_status_module can be used to enable Nginx's nginxstatus function to monitor the operation status of Nginx.
If you want to learn more about modules, you can view them by using the./configure–help option.

2, nginx configuration file structure
The Nginx configuration file nginx.conf is located in the Conf directory of its installation directory.
NGINX.CONF consists of multiple blocks, the outermost block being Main,main contains events and Http,http contains upstream and multiple server,server and contains multiple location:

Main (Global Settings), Server (host settings), upstream (Load balancer server settings), and location (URL matches settings at a specific place).

    • The instruction set by the main block will affect all other settings;
    • The instruction of the server block is mainly used to designate the host and port;
    • Upstream instruction is mainly used for load balancing, set up a series of back-end servers;
    • The location block is used to match the page position.

The relationship between the four: the server Inherits Main,location inheritance Server,upstream neither inherits other settings nor inherits them.
In each of these four sections, each part contains instructions that mainly contain Nginx's main module directives, Event module directives, HTTP Core module directives, and each section can also use other HTTP module directives, such as the HTTP SSL module, Httpgzip static modules and HTTP addition modules.

Global configuration of 2.1 Nginx

The code is as follows:

12345678910
User  Nobody nobody;worker_processes  2;error_log  logs/error.log  notice;pid        logs/nginx.pid; Worker_rlimit_nofile 65535; events{use     epoll;     Worker_connections      65536;}

The meanings of each configuration option are explained as follows:

    • User is a master module directive that specifies the Nginx worker process running users and user groups, which are run by default by the nobody account.
    • Worker_processes is a master module directive that specifies the number of processes that Nginx will open. Each nginx process consumes 10m~12m memory on average. It is recommended that you specify the same number of CPUs.
    • Error_log is a master module directive used to define a global error log file. The log output levels are debug, info, notice, warn, error, crit, where debug output logs are the most verbose, and crit output logs are minimal.
    • PID is a master module directive that specifies the location of the file where the process pid is stored.
    • Worker_rlimit_nofile is used to bind worker processes and CPUs, and more than 2.4 of Linux cores are available.

The Events event directive is to set the Nginx operating mode and the maximum number of connections:
Use is an event module directive that specifies Nginx's operating mode. The working modes supported by Nginx are SELECT, poll, Kqueue, Epoll, Rtsig and/dev/poll. Both select and poll are standard working modes, kqueue and epoll are efficient modes of operation, unlike Epoll used on Linux platforms and Kqueue in BSD systems. For Linux systems, theepoll mode of operation is preferred.
Worker_connections is also an event module directive that defines the maximum number of connections per session for Nginx, which defaults to 1024. The maximum number of client connections is determined by worker_processes and Worker_connections, which is max_client=worker_processes*worker_connections.
When acting as a reverse proxy, max_clients becomes: max_clients = worker_processes * WORKER_CONNECTIONS/4.
The maximum number of connections for a process is limited by the maximum number of open files for the Linux system process, and the worker_connections settings are not valid until the operating system command "Ulimit-n 65536" is executed

2.2 HTTP Server Configuration
Nginx Configuration code for HTTP server-related properties is as follows:

12345678910111213141516171819202122
Http{http{include      conf/mime.types;default_type  application/octet-stream;log_format main ' $remote _addr-$ Remote_user [$time _local] "$request" $status $bytes _sent "" $http _referer "" $http _user_agent "" "$gzip _ratio"; log_ Format Download ' $remote _addr-$remote _user [$time _local] "" $request "$status $bytes _sent" "$http _referer" "$http _ User_agent "" "$http _range" "$sent _http_content_range"; client_max_body_size  20m;client_header_buffer_size    32k;large_client_header_buffers  4 32k; Sendfile  on;tcp_nopush     on;tcp_nodelay    on;keepalive_timeout 60;client_header_timeout  10;client_ Body_timeout    10;send_timeout          10;

The meanings of each configuration option in this code are described in more detail below.
Include is a master module directive that enables you to set the files contained in the configuration file, reducing the complexity of the master configuration file. Similar to the Include method in Apache.
Default_type belongs to the HTTP Core Module directive, where the default type is a binary stream, that is, when the file type is not defined when the use of this way, for example, when the PHP environment is not configured, Nginx is not resolved, at this time, the browser to access the PHP file will appear in the Download window.

The following code implements the setting of the log format:

12345678
Log_format Main ' $remote _addr-$remote _user [$time _local] "" $request "$status $bytes _sent" "$http _referer" "$http _ User_agent "" "$gzip _ratio" '; Log_format download ' $remote _addr-$remote _user [$time _local] "$request" $status $bytes _sent ' "$http _referer" "$http _user_agent" "$http _range" "$sent _http_content_range";

The Log_format is an nginx httplog module instruction that specifies the output format of the Nginx log. Main the name of the output format for this log, which can be referenced in the following Access_log directive.

    • Client_max_body_size is used to set the maximum number of individual file bytes allowed for client requests;
    • The client_header_buffer_size is used to specify the Headerbuffer size from the client request header. For most requests, the buffer size of 1K is sufficient, and if you customize the message header or have a larger cookie, you can increase the buffer size. This is set to 32K;
    • Large_client_header_buffers is used to specify the maximum number and size of caches for large headers in a client request, "4" is the number, "128K" is the size, and the maximum cache volume is 4 128K;
    • The Sendfile parameter is used to turn on efficient file transfer mode. Set the Tcp_nopush and tcp_nodelay two instructions to on to prevent network congestion;
    • Keepalive_timeout sets the time-out for client connections to remain active. After this time is exceeded, the server shuts down the connection;
    • Client_header_timeout sets the client request header read time-out. If the client has not sent any data over this time, Nginx will return the "Request Time Out (408)" error;
    • Client_body_timeout sets the client request principal read time-out. If more than this time, the client has not sent any data, Nginx will return "Request Time Out (408)" error, the default value is 60;
    • The send_timeout specifies the time-out for responding to the client. This timeout is limited to the time between two connection activities, and if the client does not have any activity at this time, Nginx will close the connection.

2.3 Httpgzip Module Configuration
Configure the Nginx httpgzip module below. This module supports on-line real-time compressed output data stream.
See if the Httpgzip module is installed:

[Root@vps ~]#/opt/nginx/sbin/nginx  -vnginx version:nginx/1.0.14built by gcc 4.4.6 20110731 (Red Hat 4.4.6-3) (GCC) CO nfigure arguments:--with-http_stub_status_module--with-http_gzip_static_module--prefix=/opt/nginx

The/OPT/NGINX/SBIN/NGINX-V command allows you to view the compile options when installing Nginx, and the output shows that we have installed the Httpgzip module.

The following are the related property settings for the Httpgzip module in Nginx configuration:

1234567
Gzip  on;gzip_min_length  1k;gzip_buffers     4  16k;gzip_http_version  1.1;gzip_comp_level  2; Gzip_types  text/plain application/x-javascript text/css application/xml;gzip_vary on  ;

    • Gzip is used to set the Gzip module on or off, "gzip on" means to turn on gzip compression, real-time compressed output data stream;
    • Gzip_min_length sets the minimum number of bytes of pages that are allowed to compress, and the number of page bytes is obtained from the header content-length. The default value is 0, regardless of how much of the page is compressed. It is recommended to set the number of bytes greater than 1K, less than 1K may be more pressure;
    • Gzip_buffers represents the request for 4 units of 16K of memory as a compressed result stream cache, the default value is to request the same size as the original data memory space to store gzip compression results;
    • Gzip_http_version is used to set the recognition HTTP protocol version, the default is 1.1, most browsers now support Gzip decompression, using the default;
    • Gzip_comp_level is used to specify gzip compression ratio, 1 compression ratio is minimal, processing speed is the fastest, 9 compression ratio is the largest, transmission speed, but processing the slowest, but also consumes CPU resources;
    • Gzip_types is used to specify the type of compression, whether or not specified, the "text/html" type is always compressed;
    • The Gzip_vary option allows the front-end cache server to cache gzip-compressed pages, such as using squid to cache nginx-compressed data.

2.4 Load Balancing Configuration
The following sets the list of servers for load balancing:

1234567
Upstream Cszhi.com{ip_hash;server 192.168.8.11:80;server 192.168.8.12:80  down;server 192.168.8.13:8009  Max _fails=3  fail_timeout=20s;server 192.168.8.146:8080;}

Upstream is the Nginx HTTP upstream module, which uses a simple scheduling algorithm to load balance client IP to back-end servers.
In the above settings, a load balancer name cszhi.com is specified by the upstream directive. This name can be arbitrarily specified, and will be called directly in the following areas.

Nginx Load Balancer module currently supports 4 scheduling algorithms, the following are described separately, the latter two are third-party scheduling methods.

    • Polling (default): Each request is assigned to a different back-end server in chronological order, and if a server on the backend is down, the fault system is automatically rejected, so that user access is not affected;
    • Weight: Specifies the polling weights, the higher the Weight value, the higher the access probability allocated, mainly for the back end of each server performance is uneven;
    • Ip_hash: Each request is allocated according to the hash result of the access IP, so that visitors from the same IP have fixed access to a back-end server, which effectively solves the problem of the session sharing of dynamic Web pages;
    • Fair: More intelligent load balancing algorithms than the two above. This algorithm can intelligently load balance according to the page size and the load time, that is, the response time of the backend server to allocate the request, the response time is short priority allocation. Nginx itself is not support fair, if need to use this scheduling algorithm, must download Nginx Upstream_fair module;
    • Url_hash: Assigning requests by the hash result of the access URL, directing each URL to the same back-end server, can further improve the efficiency of the backend cache server. Nginx itself is not support url_hash, if you need to use this scheduling algorithm, you must install Nginx hash package.

In the HTTP upstream module, you can specify the IP address and port of the back-end server through the server directives, and you can also set the state of each back-end server in the load-balancing schedule. The commonly used statuses are:

    • Down: Indicates that the current server is temporarily not participating in load balancing;
    • Backup: Reserved Standby machine. When all other non-backup machines fail or are busy, the backup machine is requested, so the pressure of the machine is the lightest;
    • Max_fails: The number of times the request failed to be allowed, by default, 1. Returns the error defined by the Proxy_next_upstream module when the maximum number of times is exceeded;
    • Fail_timeout: The time to pause the service after a max_fails failure. Max_fails can be used with fail_timeout.

Note that when the load scheduling algorithm is Ip_hash, the state of the backend server in load balancing scheduling cannot be weight and backup.

2.5 Server Virtual Host Configuration
The configuration of the virtual host is described below.
It is recommended that the contents of the configuration of the virtual host be written into another file and then included through the include directive, which is easier to maintain and manage.

1234567
Server{listen          80;server_name    192.168.8.18  cszhi.com;index index.html index.htm index.php;root  / Wwwroot/www.cszhi.comcharset gb2312;access_log  logs/www.ixdba.net.access.log  main;

The server flag defines the start of the virtual host, listen is used to specify the service port of the virtual host, server_name is used to specify the IP address or domain name, and multiple domain names are separated by spaces. Index is used to set the default home address of the access, and the root command is used to specify the Web root of the virtual host, which can either be a relative path or an absolute path. CharSet is used to set the default encoding format for Web pages. The access_log is used to specify the access log storage path for this virtual host, and the last main is used to specify the output format of the access log.

2.6 Location URL matching configuration
URL address matching is the most flexible part of nginx configuration. Location supports regular expression matching, also supports conditional judgment matching, user can use location instruction to implement Nginx dynamic, static Web page filtering processing. Using the location URL matching configuration can also implement a reverse proxy for PHP dynamic parsing or load balancing.
The following setting uses the location directive to parse the URL of a Web page, all static files with a. gif,. jpg,. jpeg,. png,. bmp,. swf,. Expires,. This is 30 days.

1234
Location ~. *\. (gif|jpg|jpeg|png|bmp|swf) $  {                root    /wwwroot/www.cszhi.com;               Expires 30d;        }

The following setting is for all files under upload and HTML to be handled by Nginx, of course, upload and HTML directories are included in the/web/wwwroot/www.cszhi.com directory.

1234
Location ~ ^/(upload|html)/  {        root    /web/wwwroot/www.cszhi.com;        Expires 30d;        }

In this final setting, location is the filtering process for dynamic Web pages under this virtual host, which means that all files with the. jsp suffix are given to the native 8080 port processing.

1234
Location ~. *.php$ {    index index.php;    Proxy_pass http://localhost:8080;}

2.7 Stubstatus Module Configuration
The Stubstatus module is capable of obtaining Nginx's working status since the last boot, this module is not a core module and needs to be specified manually to use this feature at Nginx compilation installation.
The following instructions specify the ability to enable the get Nginx working state.

123456
Location/nginxstatus {     stub_status on      ;     Access_log              Logs/nginxstatus.log;     Auth_basic              "Nginxstatus";     Auth_basic_user_file.    /HTPASSWD;}

Stub_status is set to "on" to enable Stubstatus's work status statistics feature. The access_log is used to specify the access log file for the Stubstatus module. Auth_basic is an authentication mechanism of nginx. Auth_basic_user_file used to specify the authentication password file, because the Nginx auth_basic authentication uses the Apache compatible password file, therefore needs to use the Apache htpasswd command to generate the password file, For example, to add a test user, you can generate a password file using the following method:

/usr/local/apache/bin/htpasswd-c  /opt/nginx/conf/htpasswd Test

Then enter two password after confirmation to add user success.

To view Nginx operation status, you can enter Http://ip/NginxStatus, enter the created user name and password to see the operation status of Nginx:

Active Connections:1server accepts handled requests34561 35731 354399reading:0 writing:3 waiting:0

Active connections represents the number of currently active connections, and the third row of three numbers indicates that Nginx is currently processing 34,561 connections, successfully creating a secondary handshake, and processing a total of 354,399 requests. The last line of the reading represents the Nginx read to the client header information, writing indicates the number of header information returned to the client Nginx
, "Waiting" indicates that Nginx has finished processing and is waiting for the next request instruction when the number of resident connections.

In the last set, the error information of the virtual host is set back to the page, and the error_page instruction can be used to customize the return page of various error messages. By default, Nginx will be in the home directory of the HTML directory to find the specified return page, in particular, the return page size of these error messages must be more than 512K, the person will be replaced by IE browser default error page ie.

1234567
        Error_page  404              /404.html;        Error_page   502 503 504  /50x.html;        Location =/50x.html {            root   html;}}        }

Organized from: http://ixdba.blog.51cto.com/2895551/790611

The above describes the Nginx installation and configuration file nginxconf detailed, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    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.