Introduction to nginx and detailed configuration

Introduction to Nginx

Nginx is an open source high performance HTTP server and reverse proxy server that supports both IMAP/POP3/SMTP proxy services.
It has the following characteristics:
- It is efficient to process static files, index files, and automatic indexing.
- Fast and efficient reverse proxy to improve site performance.
- Rails and PHP are supported internally, and HTTP proxy servers are also supported for external services.Simple fault tolerance and load balancing using algorithms are also supported.
- On the performance side, Nginx is designed specifically for performance, which focuses on efficiency.Using the Poll model, you can support more concurrent connections and use less memory when large concurrencies occur.
- In terms of stability, the use of phased resource allocation technology results in low CPU resource utilization.
- High availability, hot standby support, fast start.

Nginx Installation

#Install installation tools and related libraries for deploying nginx
#The default installation of http_rewrite_module (rewriting requests using regular rules) requires the pcre Library
#The default installation of httP_gzip_module (Gzip compression) requires a zlib Library
#openssl library is required to install http_ssl_module(HTTPS/SLL)
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
#Download and unzip the nginx source package
wget http://nginx.org/download/nginx-1.10.3.tar.gz
tar -zxvf nginx-1.10.3.tar.gz
cd nginx-1.10.3
#Setting parameter parameters refers specifically to Nginx Compile Parameters
./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module
#Compile and Install
make && make install

Nginx Configuration

Configuration file structure

The configuration file is nginx/conf/nginx.conf in the installation directory
It mainly includes the following modules:
- main (Zone-wide settings)
- server (host configuration)
- upstream (Load Balancing Server Settings)
- location(URL matches specific location settings)

The configuration file structure is as follows

Configuration example

Global Configuration

#Nginx worker process runs users and user groups
#user  nobody nobody;
#Number of processes opened by Nginx, usually equal to or twice the number of CPU s, depending on hardware adjustments.
worker_processes  1;
#worker_processes auto;
#The following parameters specify which cpu is assigned to which process, generally without special specification.If necessary, use 0 and 1 to specify the allocation.
#This assumes that 1-4 processes are assigned separate cores to run and that the fifth process is assigned randomly.eg:
#worker_processes 4     #4-core CPU
#worker_cpu_affinity 0001 0010 0100 1000

#Define the global error log definition type, [debug|info|notice|warn|crit]
#error_log  logs/error.log  info;
#Specify the process ID storage file location
#pid        logs/nginx.pid;
#The theoretical value for the maximum number of file descriptors opened by a nginx process should be the maximum number of open files (ulimit-n) divided by the number of nginx processes, but nginx allocation requests are not so uniform, so it is best to match the value of ulimit-n.
#vim /etc/security/limits.conf
#  *                soft    nproc          65535
#  *                hard    nproc          65535
#  *                soft    nofile         65535
#  *                hard    nofile         65535
worker_rlimit_nofile 65535;

Event Configuration

events {
    #Use [kqueue | rtsig | epoll |/dev/poll | select | poll]; epoll model is a high-performance network I/O model in Linux kernel over version 2.6, if running on FreeBSD, use kqueue model.
    use epoll;

    #The maximum number of connections that each process can handle, and theoretically the maximum number of connections per nginx server is worker_processes*worker_connections.Theoretical value: worker_rlimit_nofile/worker_processes
    #Note: The maximum number of customers is also limited by the number of socket connections available to the system (~ 64K), so setting an unrealistic high is not good.
    worker_connections  65535;

    #worker works in serial mode (when load is reduced to some extent but server throughput is high, turn off using parallel mode)
    #multi_accept on;

    #keepalive timeout.
    #keepalive_timeout 60;

    #Buffer size for client request header.This can be set according to your system paging size. Normally a request header size will not exceed 1k, but since the system paging size is usually larger than 1k, it is set here as the paging size.
    #Page size can be obtained with the command getconf PAGESIZE.
    client_header_buffer_size 4k;

    #This specifies the cache for open files, which is not enabled by default, max specifies the number of caches, which is recommended to be the same as the number of open files, and inactive is how long it takes for a file to be deleted after it has not been requested.
    #open_file_cache max=65535 inactive=60s;

    #This refers to how often valid information is checked for the cache.
    #open_file_cache_valid 80s;

    #The minimum number of times a file is used within the inactive parameter time in the open_file_cache directive. If this number is exceeded, the file descriptor is always open in the cache. For example, if a file is not used once in the inactive time, it will be removed.
    #open_file_cache_min_uses 1;

}

Http parameters

#File extension and file type mapping table
    include mime.types;
    #Default file type
    default_type application/octet-stream;

#Log-related definitions
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    #Define the format of the log.The output is defined later.
    #1.$remote_addr and $http_x_forwarded_for record the ip address of the client;
    #2.$remote_user: Used to record client user names;
    #3.$time_local: Used to record access times and time zones;
    #4.$request: the url and http protocol used to record requests;
    #5.$status: Used to record request status;
    #6.$body_bytes_sent: Records the size of the body content of the file sent to the client;
    #7.$http_referer: Used to record visits from that page link;
    #8.$http_user_agent: Record information about client browsers
    #The path to the connection log, with the specified log format at the end.
    #access_log  logs/access.log  main;
    #Log only more severe errors to reduce IO pressure
    error_log logs/error.log crit;
    #Close Log
    #access_log  off;

    #Default encoding
    #charset utf-8;
    #hash table size for server name
    server_names_hash_bucket_size 128;
    #Maximum number of bytes a client requests for a single file
    client_max_body_size 8m;
    #Specify the hearerbuffer size from the client request header
    client_header_buffer_size 32k;
    #Specify the maximum number and size of caches for larger headers in client requests.
    large_client_header_buffers 4 64k;
    #Turn on efficient transmission mode.
    sendfile        on;
    #Prevent network congestion
    tcp_nopush on;
    tcp_nodelay on;    
    #Client connection timeout in seconds
    keepalive_timeout 60;
    #Client Request Header Read Timeout
    client_header_timeout 10;
    #Set client request principal read timeout
    client_body_timeout 10;
    #Response Client Timeout
    send_timeout 10;

#FastCGI-related parameters are designed to improve the performance of the website by reducing resource usage and improving access speed.
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;

#gzip module settings
    #Turn on gzip compressed output
    gzip on;
    #Minimum Compressed File Size
    gzip_min_length 1k;
    #Compression Buffer
    gzip_buffers 4 16k;
    #Compressed version (default 1.1, use 1.0 for front end if squid2.5)
    gzip_http_version 1.0;
    #The higher the compression level 1-9, the better the compression effect and save broadband, but consume more CPU
    gzip_comp_level 2;
    #The compression type already contains text/html by default, so there's no need to write it down or write it down, but there's a warn.
    gzip_types text/plain application/x-javascript text/css application/xml;
    #Front-end cache server caches compressed pages
    gzip_vary on;

Virtual Host Configuration

#Virtual Host Definition
    server {
        #Listening Port
        listen       80;
        #Access Domain Name
        server_name  localhost;
        #Encoding format, if different from this page format, will be automatically transcoded
        #charset koi8-r;
        #Virtual Host Access Log Definition
        #access_log  logs/host.access.log  main;
        #Match URL s
        location / {
            #Access Path, Relative or Absolute
            root   html;
            #Home page file.The following matches in order
            index  index.html index.htm;
        }

#Error Message Return Page
        #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;
        }

#Access URL s ending in.php are automatically forwarded to 127.0.0.1
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
#php script requests are all forwarded to FastCGI processing
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

#Prohibit access to.ht pages (requires ngx_http_access_module)
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
#HTTPS Virtual Host Definition
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

Reverse Proxy Configuration

#The following configuration is appended to the global variables of HTTP

#nginx connection timeout with back-end server (proxy connection timeout)
proxy_connect_timeout      5;
#Backend Server Data Return Time (Proxy Send Timeout)
proxy_send_timeout         5;
#Backend server response time (proxy receive timeout) after successful connection
proxy_read_timeout         60;
#Set the size of the buffer where the proxy server (nginx) holds user header information
proxy_buffer_size          16k;
#proxy_buffers, if the average page size is less than 32k, set this
proxy_buffers              4 32k;
#Buffer size under high load (proxy_buffers*2)
proxy_busy_buffers_size    64k;
#Set the cache folder size, greater than this value, to be passed from the upstream server
proxy_temp_file_write_size 64k;
#Reverse Proxy Cache Directory
proxy_cache_path /data/proxy/cache levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=1g;
#levels=1:2 sets the directory depth, with the first layer having one character and the second layer having two characters
#keys_zone: Set web cache name and memory cache size
#inactive: Automatically clear cache file time.
#max_size: The maximum amount of hard disk space available.
#Specify the storage path for the temporary cache file (the path needs to be in the same partition as the above path)
proxy_temp_path /data/proxy/temp

#Service Configuration
server {
    #Listen on port 80
    listen       80;
    server_name  localhost;
    location / {
        #Reverse Proxy Cache Settings command (proxy_cache zone|off, off by default, so set)
        proxy_cache cache_one;
        #Cache different times for different status codes
        proxy_cache_valid 200 304 12h;
        #Set what parameters to get the cache file name
        proxy_cache_key $host$uri$is_args$args;
        #The Web server on the back 7 can get users'real IP through X-Forwarded-For
        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 Settings
        proxy_pass   http://IP;
        #File expiration time control
        expires    1d;
    }
    #Configure manual cache cleanup (third-party module ngx_cache_purge is required to achieve this function)
    location ~ /purge(/.*) {
        allow    127.0.0.1;
        deny    all;
        proxy_cache_purge    cache_one    $host$1$is_args$args;
    }
    #Set dynamic applications ending with.jsp,.php,.jspx extensions not to be cached
    location ~.*\.(jsp|php|jspx)?$ {
        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_pass http://http://IP;
    }

Load Balance Configuration

upstream my_server_pool {
    #scheduling algorithm
    #1. Round Robin (by default, each request is assigned to a different back-end server one by one in a chronological order, which is automatically excluded if the back-end server is down loaded) (weight round robin weight)
    #2.ip_hash: Assigned based on the hash result of each request accessing IP.(session retention)
    #3.fair: Requests based on the minimum response time of the back-end server.(upstream_fair module)
    #4.url_hash: Allocated based on the hash result of the URL being accessed.(requires hash package)
    #Parameters:
    #down: means not participating in load balancing
    #Backup: Backup the server, request the backup machine when all other non-backup machines are down or busy.So this machine will have the lightest pressure.
    #max_fails: Maximum number of request errors allowed, default to 1. When the maximum number of requests is exceeded, an error defined by the proxy_next_upstream module is returned
    #fail_timeout: Pause service time after request fails.
    server 192.168.1.109:80 weight=1 max_fails=2 fail_timeout=30;
    server 192.168.1.108:80 weight=2 max_fails=2 fail_timeout=30;
}
#Load balancing calls
server {
    ...
    location / {
    proxy_pass http://my_server_pool;
    }
}

variable

The Ngx_http_core_module supports built-in variables whose names are identical to apache's built-in variables.The first is to describe the rows in the client request title, such as httpuseragent,http_cookie, and so on.There are other variables:

$content_lengthEqual to the "Content_Length"Value of.

$content_typeEqual to Request Header'Content_Type"Value of

$document_rootEquivalent to the current request root The value specified by the instruction

$document_uriand$uriequally

$hostAnd in the request headerHost"Row specified value or request Arrived server Name (noHostLine) Same

$limit_rateAllow restricted connection rates

$request_methodEquivalent to request Of method,Usually "GET"Or "POST"

$remote_addrClient ip

$remote_portClient port

$remote_userEquivalent to user name, by ngx_http_auth_basic_module Authentication

$request_filenameThe path name of the file currently requested by root oraliasandURI request Combination

$request_body_file

$request_uriComplete initial with parametersURI

$query_stringand$argsequally

$sheeme http Mode ( http,https)The only requirement is to evaluate, for example

Rewrite ^(.+)$ $sheme://example.com$; Redirect;

$server_protocolEquivalent to request Agreement, using "HTTP/Or "HTTP/

$server_addr request Arrived server Of ip,Generally, the purpose of getting the value of this variable is to make a system call.To avoid system calls, it is necessary to listen Indicated in directive ip,And use bind Parameters.

$server_nameThe name of the server where the request arrived

$server_portPort number of the server to which the request arrives

$uriEquivalent to Current request InURI,Can be different from the initial value, such as when redirecting internally or using index
Reference Article

Keywords: Nginx PHP Apache zlib

Added by smc on Wed, 29 May 2019 11:20:03 +0300