Installation and configuration of Nginx

Source: Internet
Author: User
Tags epoll nginx server

This article mainly introduces the installation and configuration of Nginx, has a certain reference value, and now share to everyone, the need for friends can refer to

Nginx Learning Practice

First, choose Nginx purpose

    1. High concurrent connections
      The official test Nginx can support 50,000 concurrent connections, the actual test can reach about 30,000, according to this calculation, daily can handle
      Hundreds of visits, using the latest epoll (Linux 2.6 kernel) and Kqueue (FreeBSD) network I/O models, while Achache uses traditional SELELCT
      Model

    2. Low memory consumption
      nginx+php (Fastcigi) server in 30,000 concurrent connection, open 10 Nginx process consumes 150MB memory (15MB*10), open 64 php-cgi
      The process consumes 1280MB of memory (20MB*64) and uses webbench for stress testing, which is still fast at 30,000 concurrency.

    3. Nginx supports load balancing

    4. Nginx Support Reverse Proxy

    5. Low cost
      It is free to use and can be used for commercial purposes, as compared to hardware load balancer switches such as F5BIG-IP, NetScaler, and so on at more than 100,000 settings hundreds of thousands of.

    6. Connection method for Nginx request
      Select,poll,kqueue,epoll

Second, install Nginx

Prepare the Environment
Linux system is CentOS 6.5 64 bit, I switch directly to root user installation
Official Document: http://nginx.org/en/

Su Root

Go to the user directory download program

Cd/usr/local/src

Now related components

Ngnix:wget Http://nginx.org/download/nginx-1.13.12.tar.gzwget http://www.openssl.org/source/ Openssl-fips-2.0.10.tar.gzwget Http://zlib.net/zlib-1.2.11.tar.gzwget ftp://ftp.csx.cam.ac.uk/pub/software/ Programming/pcre/pcre-8.40.tar.gz

Install a C + + compilation environment, as installed to skip

[Root@localhost src]# yum install gcc-c++ omit installation content ... There will be a confirmation prompt enter Y return is this OK [y/n]:y omitted installation content ...

Installation of Nginx and related components

OpenSSL installation [root@localhost src]# tar zxvf openssl-fips-2.0.10.tar.gz omit installation content ... [root@localhost src]# cd openssl-fips-2.0.10[root@localhost openssl-fips-2.0.10]#./config && Make && Make install omit installation content ... pcre install [root@localhost src]# tar zxvf pcre-8.40.tar.gz omit installation content ... [root@localhost src]# cd pcre-8.40[root@localhost pcre-8.40]#./configure && make && make install omit installation content ... . zlib install [root@localhost src]# tar zxvf zlib-1.2.11.tar.gz omit installation content ... [root@localhost src]# cd zlib-1.2.11[root@localhost zlib-1.2.11]#./configure && make && make Install omit installation content ... Nginx installation: Here first add an Nginx user group and an Nginx user for example: New user joins the FTP group,/sbin/nologin means that the user is not allowed to login (via FTP can connect), User name Nginxgroupadd-r ftpuseradd-s/sbin/nologin-g ftp-r nginx[root@localhost src]# tar zxvf nginx-1.13.12.tar.gz omit the installation content. .. [root@localhost src]# cd nginx-1.13.12[root@localhost nginx-1.10.2]#./configure--sbin-path=/usr/local/nginx/sbin \- -conf-path=/usr/local/nginx/conf/nginx.conf \--pid-path=/usr/local/nginx/logs/nginx.pid\--with-http_ssl_module \--with-pcre=. /pcre-8.40 \ #指向解压的源码目录--with-zlib=. /zlib-1.2.11 \ #指向解压的源码目录--with-openssl=. /openssl-2.0.10 \ #指向解压的源码目录--with-http_stub_status_module \ #启用 nginx nginxstatus function, used to monitor the current status of Nginx--user=nginx \-- Group=nginx[root@localhost nginx-1.10.2] #make && make install omit installation content ...

Start Nginx

Check your Nginx installation location

Whereis Nginx

Start, stop, restart commands

Start:/usr/local/nginx/sbin/nginx Restart:/usr/local/nginx/sbin/nginx-s Reload stop:/usr/local/nginx/sbin/nginx-s stop

Configuration file Open, validate

Configuration file: vim/usr/local/nginx/conf/nginx.conf Authentication profile:/usr/local/nginx/sbin/nginx-t

View Nginx Process

Ps-aux | grep nginx

View ports

NETSTAT-TULNP | grep:80      querying port services starting with 80

If you see the process, enter it in your local browser: http://localhost will see the Welcome screen; the installation was successful.
If you can enter the Nginx server IP on another machine access, but make sure that port 80 is open, then configure SSL to ensure that port 443 is open.

Nginx Configuration

1. Process configuration: The number of processes opened by Nginx depends on the number of cores of the CPU

The first thing to look at is the CPU Count command:

Cat/proc/cpuinfo

2.worker_connections Connection Number Configuration
Online advice:
If the Nginx worker_connections value setting is the 1024,worker_processes value setting is 4, the formula is calculated according to the maximum number of connections in reverse proxy mode: Maximum number of connections = worker_processes * Worker_ Connections/4
To view the relevant information, the Worker_connections recommended value in the production environment is better than 9000, plan to set an nginx to 10240, and then observe a period of time.

3.location Configuration
Syntax: location[=|~|~*|^~]/uri/{...}
Default value: No
Using fields: Server
This parameter is configured according to the different requirements of the URI, you can use the field string to match the regular expression, if you want to use regular expressions, you must make the following prefixes
~: Case Sensitive
~*: Case insensitive
^~: Suppress expression matching
=: Exact match

Example:

Location =/{    #只匹配/query    [configurationa]}location/{    #匹配任务以/start query, but regular expressions and some longer strings will be matched first   [ Configuration B]}location ^~/images/{    #匹配任何以/images/start the query and stop the search without checking the regular expression    [configuration C]}location ~*. Gif|jpg|jpeg) $ {    #匹配任何以gif, Jpg,jpeg end of file, but all/images/directory requests will be processed in configuration C    [configuration D]}error_ Page  404 403              /404.html;location =/404.html {    root   /var/christy/www/web;} Location/data {    #开启data目录浏览    autoindex on;} #类似于别名location/i/{    #当访问i的时候别名的路径就是/data/w3/images/;    alias/data/w3/images/;}

4. Address Rewriting

rewrite the main function is to implement the URL rewrite, Nginx rewrite rules using Pcre perl-compatible regular expression syntax for rule matching, If you need nginx rewrite function, before compiling nginx, you need to compile and install the Pcre library URL is a Uniform Resource locator. For example: Http://www,linkwan.com/333/welcome.htmURI is positioned by a generic resource identifier. For example: 333/welcome.htm address rewrite to use the directive if instruction rule syntax if the user's agent is Microsoft's MSIE (IE9), then in the browser input HTTP://WWW.CHRXXTYEDU.CN/DD will jump to http:// Www.christyedu.cn/msie/$1;ie10 above is mozillaif ($http _user_agent ~ msie) {Rewrite ^ (. *) $/msie/$1 break;} If the requested file name does not exist, redirect to/site/$host/images/$1if (!-f $request _filename) {rewrite ^/img/(. *) $/site/$host/images/$1 last;} Location ~* \.    (gif|jpg|png|swf|flv) $ {valid_referers none blocked www.chrXXstyedu.cn chrxxtyedu.cn;    if ($invalid _referer) {rewrite ^/(. *) Http://www.test.com/333/welcome permanent;    }//Anti-theft chain} set speed limit location/download/{limit_rate_after 500k; Limit_rate 50k;} The approximate meaning is: The user downloads reaches 500k, then controls its speed within 50k. 

5.SSL Configuration
1_chrxxtyedu.cn_bundle.crt
2_chrxxtyedu.cn.key
These two files are placed in the Conf directory
Make sure you release the 443 port!!!!

server {        listen       443 SSL;        server_name  www.chXXXtyedu.cn chrxxyedu.cn;        Ssl_certificate      1_chrxxtyedu.cn_bundle.crt;        Ssl_certificate_key  2_chrxxtyedu.cn.key;        Ssl_session_cache    shared:ssl:1m;        Ssl_session_timeout  5m;        Ssl_protocols TLSv1 TLSv1.1 TLSv1.2;        Ssl_ciphers ecdhe-rsa-aes128-gcm-sha256:high:!anull:! md5:! rc4:! DHE;        Ssl_prefer_server_ciphers on  ;        Location/{            root   /var/chxxty/www/web-https;            Index  index.html index.htm;        }    }

6. Log Management

Log_format  main  ' $remote _addr-$remote _user [$time _local] "$request" "$status                      $body _bytes_sent" $http _ Referer "                      " "$http _user_agent" "$http _x_forwarded_for";    $http the IP address of the _x_forwarded_for and $REMOTE_ADDR clients (proxy server, display Proxy service IP)    $remote _user is used to log the remote client user name    $time _ Local is used to record the access time and the time zone    $request The URL that is used to record the request and the HTTP protocol    $status used to record the request status, such as success is a status of 200, 404 $body When the page is not found    _bytes_ Sent is used to record the size of the file subject content that is sent to the client    $http _referer is used to record which page links are accessed from    $http _user_agent to record information about the client browser

7. Introduction to Partial caching

Open_log_file_cache instruction Syntax: Open_log_file_cache max=n [Inactive=time] [min_uses=n] [Valid=time];open_log_file_cache off Default value: Open_log_file_cache off; configuration segment: HTTP, server, location for each log record, the file is opened, written to the log, and then closed. You can use Open_log_file_cache to set the log file cache (which is off by default) in the following format: parameter comments are as follows: Max: Sets the maximum number of file descriptors in the cache and, if the cache is full, closes the descriptor with the LRU algorithm. Inactive: Set the survival time, default is 10smin_uses: set in inactive time period, the log file is used at least how many times, the log file descriptor is recorded in the cache, the default is 1 times valid: Set the check frequency, Default 60soff: Disable the cache instance as follows: The code is as follows: Open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;http {client_max_body_size 300m    ;    Client_body_buffer_size 600;    Proxy_connect_timeout 600;    Proxy_read_timeout 600;    Proxy_send_timeout 600;    Proxy_buffer_size 16k;    Proxy_buffers 4 32k;    Proxy_busy_buffers_size 64; Proxy_temp_file_write_size 64k; Allows the maximum number of individual file bytes requested by a client client_max_body_size buffer proxy buffer The maximum number of bytes requested by the user can be understood as the time-out before saving to local and then to the user client_body_buffer_size connection to the backend server Initiate handshake wait Response timeout proxy_connect_timeout After the connection is successful _ wait for the backend server response time _ actually entered the back end of the queue waiting for processing proxy_read_timeout back-end server data return time _ Is that the backend server must pass all the data within the specified time Proxy_send_timEout Proxy Request Buffer _ This cache interval will save the user's header information for Nginx rules processing _ generally as long as the head information can be saved Proxy_buffer_size 16k above tells Nginx to save a single use of a few buffers and the largest use of how much space proxy _buffers 4 32k If the system is very busy can apply for a larger Proxy_bufers official recommendation, Proxy_busy_buffers_size 64k; Proxy caches the size of the temporary file proxy_temp_file_write_size 64k;    location/sms {Proxy_pass http://127.0.0:8080;    #设置Host是真实浏览器的, not the agent's Proxy_set_header Host $host;    Proxy_cache Cache_one; #设置请求ip是真实的ip, instead of acting proxy_set_header x-forwarded-for $remote _addr; }

8. Proxy, reverse proxy, and load balancer

The concept of a forward proxy

Forward agent, that is, the legendary agent, he works like a springboard, simply said, I am a user, I can not access a website, but I have access to a proxy server This proxy server, he can access the site I cannot access so I first connected to the proxy server, Tell him I need the content proxy server that can't access the site to fetch it back, and then return it to me normal situation: client-(send request), Server Agent condition: client-(send request), Clinet Proxy – Server (send request)

What is reverse proxy?

The process of proxy in the forward proxy is the client, the agent machine is the identity of the customer, and the proxy machine is the service identity in the reverse proxy. The process of proxy in the forward proxy is the client, the server is unaware of the presence of the agent, and the client is not aware of the presence of the proxy in the reverse proxy. Reverse Proxy condition: clinet– (send request) –> server proxy– (send request) –>other server
Nginx set reverse proxy and load balancing in one, in the configuration file can be modified to implement upstream Xxx{};upstream module is named a back-end server group, the group name must be (proxy_pass name) back-end server site domain name, Internal can write more than one server IP and port, you can also set jump rules and weights and so on Proxy_pass; on behalf of the back-end server group name, this group name must be the same as the group name of the backend server site domain name server_name and upstream{}, Server_        Name is the domain name that the extranet accesses to receive the request, the group name of upstream{} is the domain name upstream chxxty_server {server 119.29.54.177:8081 weight=5 that the site accesses when jumping back-end server; Server 119.29.54.177:8080 weight=10 max_fails=3 fail_timeout=30s;}        server {listen 443 SSL;        server_name www.chXXtyedu.cn chxxxedu.cn;        Ssl_certificate 1_CHXXTYEDU.CN_BUNDLE.CRT;        Ssl_certificate_key 2_chxxyedu.cn.key;        Ssl_session_cache shared:ssl:1m;        Ssl_session_timeout 5m;        Ssl_protocols TLSv1 TLSv1.1 TLSv1.2; Ssl_ciphers ecdhe-rsa-aes128-gcm-sha256:high:!anull:! md5:! rc4:!        DHE;        Ssl_prefer_server_ciphers on;            Location/{root HTML;        Index index.html index.htm;                } location ~. * {Proxy_pass http://chxxty_server; #设置HoST is the real browser, not the agent of the Proxy_set_header Host $host;        #设置请求ip是真实的ip, instead of acting proxy_set_header x-forwarded-for $remote _addr; }}

Wish everyone success!

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.