Nginx server installation and configuration file introduction

Source: Internet
Author: User
Tags epoll openssl perl regular expression sendfile versions centos nginx server nginx reverse proxy

1. Install nginx
1.1 select stable version
We compile and install nginx to customize our own modules. The machine CentOS 6.2 x86_64. First install the missing dependency package:

# Yum-y install gcc-c ++ make libtool zlib-devel openssl-devel pcre-devel
If these software packages are not available on yum, you can download the source code for compilation and installation. You only need to pay attention to the default installation directory during compilation. Make sure that these dynamic library files (ldconfig) can be found during nginx installation ).

Download the stable nginx-1.6.3.tar.gz from the http://nginx.org/en/download.html and decompress it under/usr/local/src.

For future preparation we also download 2 plug-in modules: nginx_upstream_check_module-0.3.0.tar.gz -- check the status of the back end server, nginx-goodies-nginx-sticky-module-ng-bd312d586752.tar.gz) -- SLB on the backend solves the session sticky problem.

Pay attention to the compatibility between the plug-in and nginx versions. Generally, the newer the plug-in, the better the plug-in. nginx does not need to catch up with new ones. Nginx-1.4.7, nginx-sticky-module-1.1, nginx_upstream_check_module-0.2.0, this match is no problem. Sticky-1.1 and nginx-1.6 versions failed to catch up with compilation errors due to updates. (Tengine can be used directly. These modules are included by default)

[Root @ cachets nginx-1.6.3] # pwd
/Usr/local/src/nginx-1.6.3
[Root @ cachets nginx-1.6.3] #./configure -- prefix =/usr/local/nginx-1.6 -- with-pcre \
> -- With-http_stub_status_module -- with-http_ssl_module \
> -- With-http_gzip_static_module -- with-http_realip_module \
> -- Add-module = ../nginx-sticky-module-ng-1.2.5 -- add-module = ../nginx_upstream_check_module-0.3.0

[Root @ cachets nginx-1.6.3] # make & make install
1.2 description of common compilation options
Most common modules of nginx are installed by default when./configure -- help starts with -- without during compilation.

-- Prefix = PATH: specifies the installation directory of nginx. Default/usr/local/nginx
-- Conf-path = PATH: set the path of the nginx. conf configuration file. Nginx can be started using different configuration files through the-c option in the command line. The default value is prefix/conf/nginx. conf.
-- User = name: the user who sets the nginx worker process. After installation, you can change the user command in the nginx. conf configuration file at any time. The default user name is nobody. -- Group = name is similar
-- With-pcre: specifies the source code path of the PCRE library. If the file has been installed in yum mode, use -- with-pcre to automatically find the library file. When using -- with-pcre = PATH, you need to download the source code (version 4.4-8.30) of the PCRE library from the pcre website and decompress it. The rest will be handed over to Nginx. /configure and make. The perl regular expression is used in the location command and the ngx_http_rewrite_module module.
-- With-zlib = PATH: specifies the zlib (version 1.1.3-1.2.5) source code extraction directory. Zlib is required for the ngx_http_gzip_module, which is enabled by default.
-- With-http_ssl_module: Use the https protocol module. By default, this module is not built. The premise is that openssl and openssl-devel have been installed.
-- With-http_stub_status_module: used to monitor the current state of Nginx
-- With-http_realip_module: This module allows us to change the client IP address value in the client request header (For example, X-Real-IP or X-Forwarded-), it enables the background server to record the IP address of the original client.
-- Add-module = PATH: add a third-party external module, such as nginx-sticky-module-ng or cache module. Re-compile every time a new module is added (Tengine does not need to be re-compiled when a new module is added)
Another compilation solution is provided:

./Configure \
> -- Prefix =/usr \
> -- Sbin-path =/usr/sbin/nginx \
> -- Conf-path =/etc/nginx. conf \
> -- Error-log-path =/var/log/nginx/error. log \
> -- Http-log-path =/var/log/nginx/access. log \
> -- Pid-path =/var/run/nginx. pid \
> -- Lock-path =/var/lock/nginx. lock \
> -- User = nginx \
> -- Group = nginx \
-- With-http_ssl_module \
-- With-http_stub_status_module \
-- With-http_gzip_static_module \
> -- Http-client-body-temp-path =/var/tmp/nginx/client /\
> -- Http-proxy-temp-path =/var/tmp/nginx/proxy /\
> -- Http-fastcgi-temp-path =/var/tmp/nginx/fcgi /\
> -- Http-uwsgi-temp-path =/var/tmp/nginx/uwsgi \
> -- With-pcre = ../pcre-7.8
> -- With-zlib = ../zlib-1.2.3
1.3 enable and disable nginx
# Check whether the configuration file is correct
#/Usr/local/nginx-1.6/sbin/nginx-t
#./Sbin/nginx-V # The compilation options are displayed.

# Start and close
#./Sbin/nginx # default configuration file conf/nginx. conf, specified by-c
#./Sbin/nginx-s stop
Or pkill nginx

# Restart without changing the configuration file specified at startup
#./Sbin/nginx-s reload
Or kill-HUP 'cat/usr/local/nginx-1.6/logs/nginx. Pi'
Of course, you can also manage nginx as a system service, download nginx to/etc/init. d/, modify the path in it, and grant the executable permission.

# Service nginx {start | stop | status | restart | reload | configtest}
1.4 install yum
---- Update
Installing the rpm Package in yum is much easier than compiling and installing it. Many modules are installed by default, but the disadvantage is that if you want to install a third-party module in the future, you won't be able to install it.

# Vi/etc/yum. repo. d/nginx. repo
[Nginx]
Name = nginx repo
Baseurl = http://nginx.org/packages/centos/?releasever/?basearch/
Gpgcheck = 0
Enabled = 1
The rest of the yum install nginx get done, you can also install the specified version of the yum install nginx-1.6.3 (the premise is that you go to the packages to see the corresponding version, the default is the latest stable version ).

2. nginx. conf configuration file
The Nginx configuration file is mainly divided into four parts: main (global settings), server (host settings), upstream (upstream server settings, mainly reverse proxy, server load balancer configuration) and location. Each part contains several commands. The commands set in the main section will affect the settings of all other sections. The commands in the server section are mainly used to specify the virtual host domain name, IP address, and Port. The instructions in upstream are used to set a series of backend servers, set the reverse proxy and backend server load balancer. The location part is used to match the webpage location (for example, the root directory "/", "/images", and so on ). The relationship between them: server inherits main, location inherits server; upstream neither inherits commands nor is inherited. It has its own special commands and does not need to be used elsewhere.

The following command contexts are supported by nginx:

2.1 General purpose
The nginx. conf below is a simple example of implementing nginx as a reverse proxy server at the front end, handling static files such as js and png, and forwarding dynamic requests such as jsp to tomcat on other servers:

User www;
Worker_processes 2;

Error_log logs/error. log;
# Error_log logs/error. log notice;
# Error_log logs/error. log info;

Pid logs/nginx. pid;


Events {
Use epoll;
Worker_connections 2048;
}


Http {
Include mime. types;
Default_type application/octet-stream;

# Log_format main '$ remote_addr-$ remote_user [$ time_local] "$ request "'
# '$ Status $ body_bytes_sent "$ http_referer "'
# '"$ Http_user_agent" "$ http_x_forwarded_for "';

# Access_log logs/access. log main;

Sendfile on;
# Tcp_nopush on;

Keepalive_timeout 65;

# Gzip compression settings
Gzip on;
Gzip_min_length 1 k;
Gzip_buffers 4 16 k;
Gzip_http_version 1.0;
Gzip_comp_level 6;
Gzip_types text/html text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
Gzip_vary on;

# Http_proxy settings
Client_max_body_size 10 m;
Client_body_buffer_size 128 k;
Proxy_connect_timeout 75;
Proxy_send_timeout 75;
Proxy_read_timeout 75;
Proxy_buffer_size 4 k;
Proxy_buffers 4 32 k;
Proxy_busy_buffers_size 64 k;
Proxy_temp_file_write_size 64 k;
Proxy_temp_path/usr/local/nginx/proxy_temp 1 2;

# Set the server load balancer backend server list
Upstream backend {
# Ip_hash;
Server 192.168.10.100: 8080 max_fails = 2 fail_timeout = 30 s;
Server 192.168.10.101: 8080 max_fails = 2 fail_timeout = 30 s;
    }

# Important VM configurations
Server {
Listen 80;
Server_name itoatest.example.com;
Root/apps/oaapp;

Charset UTF-8;
Access_log logs/host. access. log main;

# Load balancing and reverse proxy for/All
Location /{
Root/apps/oaapp;
Index. jsp index.html index.htm;

Proxy_pass http: // backend;
Proxy_redirect off;
# The backend Web server can use X-Forwarded-For to obtain the user's real IP address.
Proxy_set_header Host $ host;
Proxy_set_header X-Real-IP $ remote_addr;
Proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
Proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;

        }

# Static files are processed by nginx without backend requests to tomcat
Location ~ */Download /{
Root/apps/oa/fs;

        }
Location ~ . * \. (Gif | jpg | jpeg | bmp | png | ico | txt | js | css) $
        {  
Root/apps/oaapp;
Expires 7d;
        }
Location/nginx_status {
Stub_status on;
Access_log off;
Allow 192.168.10.0/24;
Deny all;
        }

Location ~ ^/(WEB-INF )/{
Deny all;
        }
# 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;
        }
    }

# Start with server commands for other virtual hosts
}

2.2 Instructions
2.2.1 main global configuration
Some parameters irrelevant to specific business functions (such as http service or email service proxy) during nginx running, such as the number of working processes and running identity.

Woker_processes 2
In the top-level main part of the configuration file, the number of worker processes of the worker role. The master process receives and assigns requests to the worker for processing. This value can be set to the number of cpu cores grep ^ processor/proc/cpuinfo | wc-l, which is also an auto value, if ssl and gzip are enabled, they should be set to the same or even double the number of logical CPUs, which can reduce I/O operations. If the nginx server has other services, you can reduce the number as needed.
Worker_cpu_affinity
It is also written in the main section. In the case of high concurrency, you can set cpu stickiness to reduce the performance loss caused by Register and other field reconstruction caused by multi-CPU core switching. For example, worker_cpu_affinity 0001 0010 0100; (quad core ).
Worker_connections 2048
In the events section. The maximum number of connections that a worker process can process (initiate) concurrently (including the number of connections between the worker and the client or the backend proxy server ). As the reverse proxy server, nginx calculates the maximum number of connections = worker_processes * worker_connections/4. Therefore, the maximum number of connections on the client is 1024. It does not matter if it can be increased to 8192. Depending on the situation, however, it cannot exceed worker_rlimit_nofile. When nginx is used as an http server, the formula is divided by 2.
Worker_rlimit_nofile 10240.
In the main section. It is not set by default. It can be set to a maximum of 65535 of the operating system.
Use epoll
In the events section. In Linux, nginx uses the epoll event model by default. Thanks to this, nginx is highly efficient in Linux. At the same time, Nginx uses an efficient event model kqueue similar to epoll on the OpenBSD or FreeBSD operating system. Select is used only when the operating system does not support these efficient models.
2.2.2 http server
Configuration parameters related to the provision of http services. For example, whether to use keepalive or gzip for compression.

Sendfile on
Enable the efficient file transmission mode. The sendfile command specifies whether nginx calls the sendfile function to output files, reducing context switching between user space and kernel space. For general applications that are set to on, if used for downloading and other application disk I/O heavy load applications, you can set it to off to balance the disk and network I/O processing speed and reduce the system load.
Keepalive_timeout 65: long connection timeout time in seconds. This parameter is very sensitive and involves the browser type, backend server timeout settings, and operating system settings. You can start another article. When a large number of small files are requested for persistent connections, the overhead of re-connection can be reduced. However, if a large file is uploaded, failed Upload within 65 seconds. If the setting takes too long and there are too many users, it will take a lot of resources to maintain the connection for a long time.
Send_timeout: Used to specify the timeout time for the response client. This timeout is limited to the time between two connection activities. If the time exceeds this time and the client does not have any activity, Nginx will close the connection.
Client_max_body_size 10 m
Maximum number of bytes per file allowed by the client. If a large file is uploaded, set the limit.
Client_body_buffer_size 128 k
Maximum number of bytes requested by the buffer proxy to buffer the client
Module http_proxy:
This module implements nginx as a reverse proxy server, including the cache function (see the article)

Proxy_connect_timeout 60
Timeout time for nginx connection to backend servers (proxy connection timeout)
Proxy_read_timeout 60
Timeout between two successful response operations (proxy receiving timeout) with the backend server after successful connection)
Proxy_buffer_size 4 k
Sets the buffer size for the proxy server (nginx) to read and save user header information from the backend realserver. By default, the buffer size is the same as that of proxy_buffers. In fact, this command value can be smaller.
Proxy_buffers 4 32 k
Proxy_buffers buffer. nginx caches responses from the backend realserver for a single connection. If the average webpage size is below 32 kB, this setting
Proxy_busy_buffers_size 64 k
Buffer size under high load (proxy_buffers * 2)
Proxy_max_temp_file_size
When proxy_buffers does not fit the response content of the backend server, part of the content will be saved to the temporary files on the hard disk. This value is used to set the maximum temporary file size. The default value is 1024 MB, which has no relationship with proxy_cache. If the value is greater than this value, it will be returned from the upstream server. Set to 0 to disable.
Proxy_temp_file_write_size 64 k
When the cache is responded to a temporary file by the proxy server, this option limits the size of each temporary file written. Proxy_temp_path (which directory can be written during compilation.
Proxy_pass and proxy_redirect can be found in the location section.

Module http_gzip:

Gzip on: enables gzip compression output to reduce network transmission.

Gzip_min_length 1 k: set the minimum number of bytes of the page that can be compressed. The number of bytes of the page is obtained from the content-length header of the header. The default value is 20. We recommend that you set the size to 1 kb. Smaller than 1 KB may increase the pressure.
Gzip_buffers 4 16 k: set the system to obtain several units of cache for storing gzip compressed result data streams. 4 16 K indicates that the size of the original data is 4 times the size of the requested memory in 16 K.
Gzip_http_version 1.0: used to identify the http protocol version. Early browsers do not support Gzip compression and users will see garbled characters. Therefore, this option is added to support earlier versions, if you use Nginx Reverse proxy and want to enable Gzip compression, set it to 1.0 because the end communication is http/1.0.
Gzip_comp_level 6: gzip compression ratio. 1. The minimum compression ratio is the fastest. 9. The maximum compression ratio is the lowest, but the processing speed is the slowest (fast transmission but cpu consumption is relatively high)
Gzip_types: the mime type is compressed. Whether specified or not, the "text/html" type is always compressed.
Gzip_proxied any: when Nginx is enabled as the reverse proxy, it determines whether to enable or disable the backend server's returned results for compression. The prerequisite for matching is that the backend server must return the header containing ".
Gzip_vary on: is related to the http header. A Vary: Accept-Encoding is added to the response header, which allows the front-end cache server to cache pages compressed by gzip. For example, use Squid to cache data compressed by Nginx ..
2.2.3 server virtual host
The http service supports several virtual hosts. Each virtual host has a corresponding server configuration item, which contains configurations related to the virtual host. You can also create several servers when providing the mail service proxy. Each server is differentiated by the listening address or port.

Listen
Listening port. The default value is 80. If the port is smaller than 1024, it must be started as root. It can be in the form of listen *: 80 or listen 127.0.0.1: 80.
Server_name
The server name, such as localhost and www.example.com, can be matched by regular expressions.
Module http_stream
This module uses a simple scheduling algorithm to achieve load balancing between the client IP address and the backend server. upstream is followed by the name of the server load balancer, and the backend realserver uses host: port options; the mode is organized in. If the backend has only one proxy, you can directly write it in proxy_pass.

2.2.4 location
A series of configuration items corresponding to some specific URLs in the http service.

Root/var/www/html
Defines the default website root directory location of the server. If the locationURL matches a subdirectory or file, root does not work. It is generally placed in the server command or under.
Index. jsp index.html index.htm
Defines the default access file name in the path, usually followed by the root
Proxy_pass http:/backend
Requests are redirected to the backend defined server list, that is, reverse proxy, corresponding to the upstream load balancer. You can also use proxy_pass http: // ip: port.
Proxy_redirect off;
Proxy_set_header Host $ host;
Proxy_set_header X-Real-IP $ remote_addr;
Proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
For the time being, these four settings will be explained in another article.
Location matching rules are particularly critical and basic. Refer to nginx configuration location Summary and rewrite rule writing;

2.3 Others
2.3.1 access control allow/deny
Nginx's access control module will be installed by default, and the writing method is also very simple, you can have multiple allow, deny, respectively, allow or prohibit access to an ip address or ip segment, if any rule is satisfied in turn, the matching will be stopped. For example:

Location/nginx-status {
Stub_status on;
Access_log off;
# Auth_basic "NginxStatus ";
# Auth_basic_user_file/usr/local/nginx-1.6/htpasswd;

Allow 192.168.10.100;
Allow 172.29.73.0/24;
Deny all;
}
We also use the httpd-devel tool's htpasswd to set a logon password for the access path:

# Htpasswd-c htpasswd admin
New passwd:
Re-type new password:
Adding password for user admin

# Htpasswd admin // change the admin password
# Htpasswd sean // add one more authenticated user
In this way, a password file encrypted with CRYPT is generated by default. Open the above two lines of nginx-status comments and restart nginx to take effect.

2.3.2 List directory autoindex
By default, Nginx does not allow listing the entire directory. To enable this function, open the nginx. conf file and add autoindex on to the location, server, or http segment. It is best to add the following two parameters:

Autoindex_exact_size off; the default value is on. The exact size of the file is displayed, in bytes. After changing to off, the approximate size of the file is displayed. The unit is kB, MB, or GB.
Autoindex_localtime on;
The default value is off. The displayed file Time Is GMT. After changing to on, the displayed File time is the file server time
Location/images {
Root/var/www/nginx-default/images;
Autoindex on;
Autoindex_exact_size off;
Autoindex_localtime on;
  }

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.