Compile install and configure nginx under CentOS

  • 2020-05-10 23:31:57
  • OfStack

1. Install nginx

1.1 select the stable version

We compile and install nginx to customize our own module, machine CentOS 6.2 x86_64 . First install the missing dependencies:

# yum -y install gcc gcc-c++ make libtool zlib zlib-devel openssl openssl-devel pcre pcre-devel

You can download the source code to compile and install these packages if they are not available on yum. Just be aware of the directory that is installed by default at compile time and make sure you can find these dynamic library files (ldconfig) when you install nginx below.

From http: / / nginx org/en/download html download stable version nginx-1.6.3.tar.gz Unzip to /usr/local/src.

In order to prepare for the future, we will download two additional 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 (it is recommended to rename the directory to nginx-sticky-module-ng-1.2.5 after decompression under /usr/local/src) -- load balancing is done at the back end to solve the session sticky problem.

Please note that the plugin is compatible with the version of nginx. The newer the plugin is, the better. nginx does not need to be updated. nginx-1.4.7, nginx-sticky-module-1.1, nginx_upstream_check_module-0.2.0, no problem with this collocation. The sticky-1.1 and nginx-1.6 versions failed to keep up with the compilation due to updates. (you can use Tengine directly, including these modules 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 nginx modules are installed by default at compile time./configure --help starts with --without.

--prefix=PATH: specify the installation directory for nginx. The default/usr/local/nginx -- conf-path =PATH: sets the path to the nginx.conf configuration file. nginx allows you to start with a different configuration file, using the -c option on the command line. Defaults to prefix conf/nginx conf --user=name: user who sets the nginx worker process. Once the installation is complete, you can change the user directive at any time in the nginx.conf configuration file. The default user name is nobody. - group = name similar -- with-pcre: sets the source path of the PCRE library. If it is installed by yum, use -- with-pcre to automatically find the library files. To use -- with-pcre =PATH, download the source code (version 4.4-8.30) of the pcre library from the PCRE website and unzip it, leaving the rest to Nginx's./configure and make. perl regular expressions are used in the location directive and the ngx_http_rewrite_module module. -- with-zlib =PATH: specify the source unzip directory for zlib (version 1.1.3-1.2.5). zlib is used when the network transport compression module ngx_http_gzip_module is enabled by default. -- with-http_ssl_module: use the https protocol module. By default, the module is not built. The premise is that openssl and openssl-devel have been installed -- with-http_stub_status_module: 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-For), in order to enable the backend server to record the original client IP address -- add-module =PATH: add a third external module, such as nginx-sticky-module-ng or cache module. Recompile every time a new module is added (Tengine can be added without recompiling when module is added)

Another compilation scheme is provided:


./configure \
> --prefix=/usr \
> --sbin-path=/usr/sbin/nginx \
> --conf-path=/etc/nginx/nginx.conf \
> --error-log-path=/var/log/nginx/error.log \
> --http-log-path=/var/log/nginx/access.log \
> --pid-path=/var/run/nginx/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 start and close nginx


##  Check that the configuration file is correct 
# /usr/local/nginx-1.6/sbin/nginx -t 
# ./sbin/nginx -V   #  You can see the compile options 

##  Start and close 
# ./sbin/nginx    #  Default profile  conf/nginx.conf . -c  The specified 
# ./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. pid `
Of course can also be nginx as the service management system, download nginx to/etc init. d /, modify the path of the inside and then give the executable permissions.


# service nginx {start|stop|status|restart|reload|configtest} 

1.4 yum installation

Installing the yum package is much easier than compiling and installing it. Many modules are installed by default, but the downside is that if you want to install a third module later, you won't be able to.


# 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 is yum install nginx We're done. We can do it yum install nginx-1.6.3 Install the specified version (if you go to packages and see the corresponding version, the default is the latest stable version).

2. nginx.conf configuration file

The Nginx configuration file is divided into four parts: main (global setting), server (host setting), upstream (upstream server setup, mainly reverse proxy, load balancing related configuration) and # yum -y install gcc gcc-c++ make libtool zlib zlib-devel openssl openssl-devel pcre pcre-devel
0 (Settings after URL matches a specific location), each section contains several instructions. Instructions set in part main will affect the Settings of all other parts; The server part of the directive is mainly used to specify the virtual host domain name, IP and port; The instruction of upstream is used to set up the back-end servers of series 1 and set up the load balancing of the reverse proxy and back-end servers. The location section matches the page location (for example, the root directory "/", "/images", and so on). The relation between them is: server inherits main, location inherits server; upstream neither inherits instructions nor is inherited. It has its own special instructions that need not be applied elsewhere.

Several instruction contexts currently supported by nginx:

2.1 general

nginx. conf simply implements nginx as a reverse proxy server at the front end, processing static files such as js and png, and forwarding dynamic requests such as jsp to other servers, tomcat:


user www 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 function setting 
  gzip on;
  gzip_min_length 1k;
  gzip_buffers  4 16k;
  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  Set up the 
  client_max_body_size  10m;
  client_body_buffer_size  128k;
  proxy_connect_timeout  75;
  proxy_send_timeout  75;
  proxy_read_timeout  75;
  proxy_buffer_size  4k;
  proxy_buffers  4 32k;
  proxy_busy_buffers_size  64k;
  proxy_temp_file_write_size 64k;
  proxy_temp_path  /usr/local/nginx/proxy_temp 1 2;

 #  Set the load balancing backend server list  
  upstream backend { 
       #ip_hash; 
       server  192.168.10.100:8080 max_fails=2 fail_timeout=30s ; 
       server  192.168.10.101:8080 max_fails=2 fail_timeout=30s ; 
  }

 #  Very important virtual host configuration 
  server {
    listen    80;
    server_name itoatest.example.com;
    root  /apps/oaapp;

    charset utf-8;
    access_log logs/host.access.log main;

    # right  /  All do load balancing + The reverse proxy 
    location / {
      root  /apps/oaapp;
      index index.jsp index.html index.htm;

      proxy_pass    http://backend; 
      proxy_redirect off;
      #  The back end Web The server can go through X-Forwarded-For Get user real IP
      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, nginx Deal with it. Don't go backend request 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 504 /50x.html;
    location = /50x.html {
      root  html;
    }
  }

 ##  Other virtual hosts, server  Order began 
}

2.2 description of common instructions

2.2.1 main global configuration

Some parameters, such as the number of worker processes, the identity of the run, etc. that are not related to the specific business function (such as http service or email service proxy) at run time of nginx.

woker_processes 2

In the top-level main section of the configuration file, the number of worker processes for the worker role, and the master process is the one that receives and assigns requests to the worker process. grep ^processor /proc/cpuinfo | wc-l is also auto value. If ssl and gzip are turned on, ssl and gzip should be set to 1 or even 2 times the number of logical CPU, which can reduce the operation of I/O. If the nginx server has other services, consider reducing them.

worker_cpu_affinity

Also written in section main. In the case of high concurrency, the viscosity of cpu is set to reduce the performance loss caused by field reconstruction such as register switching caused by multi-CPU core switching. For example, worker_cpu_affinity 0001 0010 0100 1000; (4 cores).

worker_connections 2048

Write it in section events. The maximum number of connections (including all connections to the client or back-end proxy) that can be processed (initiated) concurrently per 1 worker process. As a reverse proxy server, nginx is calculated as the maximum number of connections = worker_processes * worker_connections/4, so the maximum number of connections of the client is 1024. It doesn't matter if it can be increased to 8192, but it cannot exceed worker_rlimit_nofile. When nginx is the http server, the calculation formula is divided by 2.

worker_rlimit_nofile 10240

Write it in section main. The default is unset and can be limited to the maximum operating system limit of 65535.

use epoll

Write it in the events section. With the Linux operating system, nginx USES the epoll event model by default. Thanks to this, nginx is quite efficient with the Linux operating system. At the same time, Nginx USES epoll's efficient event model kqueue on OpenBSD or FreeBSD operating systems. Use select when the operating system does not support these efficient models.

2.2.2 http server

Some configuration parameters related to providing http services. For example, whether to use keepalive, whether to use gzip for compression, etc.

sendfile on:
With efficient file transfer mode enabled, the sendfile directive specifies whether nginx calls the sendfile function to output the file, reducing the context switching from user space to kernel space. For common applications, on can be set to off if it is used for loading applications such as application disk IO, so as to balance the processing speed of disk and network I/O and reduce the load of the system.
keepalive_timeout 65 :
Long connection timeout, in seconds, is a very sensitive parameter, involving the type of browser, back-end server timeout Settings, operating system Settings, you can start another piece of article. Long connection requests for a large number of small files can reduce the overhead of rebuilding the connection, but if a large file is uploaded, it will fail if the upload is not completed in 65s. If the setup time is too long and there are too many users, keeping the connection for a long time will take up a lot of resources.
send_timeout :
Used to specify a timeout for the response client. This timeout is limited to the time between the two connection activities, and if the client has no activity beyond this time, Nginx will close the connection. client_max_body_size 10m:
Maximum number of bytes per file allowed for client request. If you upload a large file, set its limit value client_body_buffer_size 128k:
The buffer agent buffers the maximum number of bytes requested by the client

Module http_proxy:
This module implements nginx as a reverse proxy server, including caching (see also article)

proxy_connect_timeout 60: nginx connection timeout with back-end server (proxy connection timeout) proxy_read_timeout 60: timeout between two successful response operations with the backend server after a successful connection (proxy receive timeout) proxy_buffer_size 4k: set the buffer size of the proxy server (nginx) to read and save the user header from the backend realserver. By default, it is the same size as proxy_buffers proxy_buffers 4 32k: proxy_buffers buffer, nginx cache responses from the backend realserver for a single connection, if the average page is below 32k proxy_busy_buffers_size 64k: buffer size under high load (proxy_buffers*2) proxy_max_temp_file_size: when proxy_buffers cannot fit the response content of the back-end server, part 1 will be saved to a temporary file on the hard disk. This value is used to set the maximum temporary file size. The default is 1024M, which is not related to proxy_cache. Greater than this value will be returned from the upstream server. Set to 0 to disable. proxy_temp_file_write_size 64k: this option limits the size of the temporary file each time it is written when the proxy server responds to the temporary file. proxy_temp_path (at compile time) specifies which directory to write to. For proxy_pass, see location for proxy_redirect.

Module http_gzip:

gzip on: turn on gzip compressed output to reduce network traffic. gzip_min_length 1k: sets the minimum number of page bytes allowed to be compressed, which is obtained from content-length header. The default value is 20. It is recommended to set it to the number of bytes greater than 1k. If it is less than 1k, the more pressing it will be. gzip_buffers 4 16k: set up the system to get several units of cache to store the compressed result data stream of gzip. 4 16k represents the requested memory in units of 16k and the installed original data size in units of 16k. gzip_http_version 1.0: used to identify the version of http protocol. Early browsers did not support Gzip compression, so users would see the messy code, so this option was added to support the previous version. If you use Nginx's reverse proxy and expect Gzip compression to be enabled, please set it to 1.0 because the terminal communication is http/1.0. gzip_comp_level 6: gzip compression ratio, 1 minimum compression ratio, fastest processing speed, 9 maximum compression ratio, slowest processing speed (fast transmission but relatively consuming cpu) gzip_types: matches the mime type for compression, and the "text/html" type will always be compressed whether or not specified. gzip_proxied any: when Nginx is enabled as a reverse proxy, it determines whether the result returned by the back-end server is compressed or not. The matching premise is that the back-end server must return the header header containing "Via". gzip_vary on: related to the http header, Vary: Accept-Encoding is added to the response header to enable the front-end cache server to cache the gzip compressed pages. For example, Squid is used to cache the Nginx compressed data.

2.2.3 server virtual host

Several virtual hosts are supported on the http service. Each virtual host has a corresponding server configuration item, which contains the configuration related to the virtual host. Several server can also be set up when providing an agent for the mail service. Each server is distinguished by listening on the address or port.

listen: listen to port, default 80, less than 1024 to start with root. It can be in the form of listen *:80, listen 127.0.0.1:80, etc. server_name: the server name, such as localhost, www.example.com, can be matched regularly.

Module http_stream

This module realizes load balancing from the client IP to the back-end server through a simple scheduling algorithm. upstream is followed by the name of the load balancer. The back-end realserver is followed by host:port options; The mode is organized in {}. If only one backend is being proxied, it can also be written directly in proxy_pass.

2.2.4 location
In the http service, some specific URL configuration items correspond to the 1 series.

root /var/www/html    defines the default site root location for the server. If locationURL matches a subdirectory or file, root doesn't work, 1 is usually placed in or under the server directive.

index index.jsp index.html index.htm defines the file name to be accessed by default in the path, 1 generally followed by root

proxy_pass http:/backend The request goes to the list of servers defined by backend, the reverse proxy, corresponding to the upstream load balancer. Can also be 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, let's assume that each of the four involves very complex content and will be interpreted through another article.

Regarding the writing method of location matching rules, it can be said that it is particularly critical and basic. Refer to the summary of nginx configuration location and the writing method of rewrite rules in the article nginx.

2.3 other

2.3.1 access control allow/deny

The access control module of Nginx will be installed by default, and the writing method is also very simple, there can be multiple allow,deny, respectively, allow or disable a certain ip or ip segment access, in order to meet any one of the rules will stop down the match. Such as:


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 htpasswd of the httpd-devel tool to set the login password for the access path:


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

# htpasswd htpasswd admin  // Modify the admin password 
# htpasswd htpasswd sean  // How to add 1 Individual authenticated user 

This generates a password file encrypted with CRYPT by default. Open the above two lines of nginx-status comments and restart nginx to take effect.

2.3.2 list the directory autoindex

Nginx is not allowed to list entire directories by default. To do this, open the nginx.conf file and add autoindex on to location, server or http; , and the other two parameters should be added:

autoindex_exact_size off; The default is on, which shows the exact size of the file in bytes. When changed to off, the approximate size of the file is shown in kB or MB or GB
autoindex_localtime on;
The default is off, and the file time displayed is GMT. After changing to on, the time of the file displayed is the server time of the file


location /images {
 root  /var/www/nginx-default/images;
 autoindex on;
 autoindex_exact_size off;
 autoindex_localtime on;
 }

reference

http://liuqunying.blog.51cto.com/3984207/1420556
http://nginx.org/en/docs/ngx_core_module.html#worker_cpu_affinity
http://wiki.nginx.org/HttpCoreModule#sendfile


Related articles: