Build Nginx server and its configuration file Detailed

Bowen outline:

  • A, Nginx Introduction
  • Second, set up Nginx server
  • Third, the upgrade to version 1.2 Nginx services
  • Fourth, Nginx modify header information service
  • V. Detailed nginx main configuration file location options
  • Sixth, Nginx configuration access https

A, Nginx Introduction

Nginx developed specifically for performance optimization, its biggest advantage is its low stability and consumption of system resources, as well as high processing capacity http concurrent connections, a single physical server can support concurrent requests 20,000 to 50,000, is the case, providing a large number of social networking, news, e-commerce and web hosting, and service companies have chosen to provide Nginx web services, mainland China use nginx web site users are: Sina, Netease, Tencent, another well-known micro-blog Plurk also use nginx .

Nginx is a very high-performance Web cattle and reverse proxy server, which has had a lot of very superior characteristics:

  • High concurrent connections: official test can support 50,000 concurrent connections, went 2 in the actual production environment, ~ 3W concurrent connections.
  • Less memory consumption: 3W of concurrent connections, open 10 NGINX process consumes only 150M memory (15M * 10 = 150M)
  • Configuration file is very simple: with the program as easy to understand style.
  • Cost: Nginx as open source software, free to use, and the purchase F5 BIG-IP, NetScaler load balancing switches and other hardware is required tens of thousands to hundreds of thousands of yuan.
  • Support rewrite rewrite rule: can according to different URL domain name, HTTP requests are distributed to different back-end server group.
    Built-in health check function: if Nginx Proxy back end of back-end web server goes down, will not affect front-end access.
  • Save Bandwidth: supports GZIP compression, you can add a local browser cache Header head.
  • High stability: a reverse proxy, the probability of downtime is minimal.

For a Web server, the request is a basic process: establishing a connection - the received data - data transmission, the system appears to the bottom: the above process (a connection - the received data - data transmission) is to write the underlying event in the system.
If by way of blocking calls, read and write when the event is not ready, then it can only wait for the current thread is suspended, other events ready for reading and writing events.
If by way of non-blocking calls: return immediately event, an event not ready to tell you, it would come back. After a while, check the event again until the ready event so far, during which you'll be able to do other things, and then look at the events to be yet. Although it is not blocked, but when you come Debu to check the status of an event, you can do more things, but the overhead is not small. Before non-blocking call refers not get the results immediately, the call does not block the current thread

By constantly checking the state of non-blocking event to determine whether read and write operations, so bring a lot of overhead, so there will be a non-blocking asynchronous event handling mechanism. This mechanism allows you to simultaneously monitor multiple events, they are non-blocking calls, but you can set the timeout within the timeout period, if there is an event ready to return. This mechanism solves two problems above blocking calls and non-blocking calls.
To epoll model as an example: when the event is not ready, they put epoll (queue) inside. If an event is ready, then go deal; when the event is not ready, just waiting for the epoll inside. In this way, we can handle a large number of concurrent concurrent, of course, where the concurrent requests, refer the request to the untreated finish. Only one request thread, so, of course, at the same time can handle only one, just be constantly switching it between requests, but also due to the asynchronous switching event is not ready, and take the initiative to get out of. Switch here is not any price, it can be understood handle multiple events ready for the cycle.
Multi-threaded mode, this kind of event handling is a great advantage, do not need to create a thread for each request takes very little memory, no context switching, event handling is very lightweight, with a few more it will not lead to unnecessary waste of resources (context switching). For apache server, each request will be exclusively a worker thread, when several thousand to the number of concurrent, they also have thousands of threads handle requests. This operating system, is no small challenge: because the thread brought very large memory footprint, a great thread context switching overhead to bring cpu, natural performance would not increase, resulting in performance under high concurrency scenarios serious decline.
Summary: non-blocking asynchronous event handling mechanism, Nginx achieved by the process loop ready to handle multiple events, in order to achieve high concurrency and lightweight.

Second, set up Nginx server

Preparing the environment:

  • centos 7.3, IP address is 192.168.20.5
  • Download the package I provide, without having to download all, what can later be used to download anything.

Note: Nginx official Download: http://nginx.org/download/

1, the nginx-1.14.0.tar.gz uploaded to the server (because there is a later upgrade Nginx operation, so a lower version installed Nginx)

[root@nginx ~]# rz       #在xshell中上传所需源码包
[root@nginx ~]# tar zxf nginx-1.14.0.tar.gz -C /usr/src  #解包
[root@nginx ~]# cd /usr/src/nginx-1.14.0/   #切换至解压后的目录
[root@nginx nginx-1.14.0]# useradd -M -s /sbin/nologin nginx   #创建运行Nginx的用户 
[root@nginx nginx-1.14.0]# yum -y erase httpd   #卸载系统自带的httpd服务,以免冲突
[root@nginx nginx-1.14.0]# yum -y install openssl-devel pcre-devel
[root@nginx nginx-1.14.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module && make && make install 

At this point, the installation is successful

Third, the upgrade to version 1.2 Nginx services

[root@nginx nginx-1.14.0]# /usr/local/nginx/sbin/nginx    #启动Nginx服务
[root@nginx nginx-1.2.4]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.14.0    #注意,现在版本为nginx/1.14.0
            .......................#省略部分信息
[root@nginx ~]# rz        #在xshell中上传所需源码包

[root@nginx ~]# tar zxf nginx-1.2.4.tar.gz -C /usr/src   #解压
[root@nginx ~]# cd /usr/src/nginx-1.2.4/   #切换至解压后的路径
[root@nginx nginx-1.2.4]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module && make
#注意,升级时,不要执行make install 命令,否则会覆盖原有的低版本配置文件
[root@nginx nginx-1.2.4]# pwd    #确认当前路径
/usr/src/nginx-1.2.4 
[root@nginx nginx-1.2.4]# mv /usr/local/nginx/sbin/nginx nginx.bak
#将旧版本的服务控制命令进行更名
[root@nginx nginx-1.2.4]# cp objs/nginx /usr/local/nginx/sbin/   #复制新生成的控制命令至指定目录
[root@nginx nginx-1.2.4]# kill -USR2 `cat /usr/local/nginx/logs/nginx.pid`
#生成新的PID号
[root@nginx nginx-1.2.4]# kill -HUP `cat /usr/local/nginx/logs/nginx.pid`   #重启Nginx服务
[root@nginx nginx-1.2.4]# /usr/local/nginx/sbin/nginx -V   #查看是否已经升级
nginx version: nginx/1.2.4     #版本为1.2.4,升级成功

Fourth, Nginx modify header information service

Generally intended to improve security, we will have the client version of Nginx information hiding, as follows:

#修改前,客户端访问,可以看到我们Nginx服务器的版本等信息,如下:
[root@nginx nginx-1.2.4]# curl -I 127.0.0.1    #获取头部信息
HTTP/1.1 200 OK
Server: nginx/1.2.4      #版本信息显示的很详细
Date: Thu, 17 Oct 2019 14:40:50 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 17 Oct 2019 14:20:40 GMT
Connection: keep-alive
Accept-Ranges: bytes
#现在进行修改如下:
[root@nginx nginx-1.2.4]# pwd   #确定当前工作路径在源码包中
/usr/src/nginx-1.2.4
[root@nginx nginx-1.2.4]# vim src/core/nginx.h    #修改该文件,随便修改即可
#define nginx_version      1002004
#define NGINX_VERSION      "666"   #这里为版本号信息
#define NGINX_VER          "ljz/" NGINX_VERSION    #这里原来为Nginx,现更改为ljz
#注意,上述配置项前面的注释符号不用删除
#更改完成后,保存退出即可
[root@nginx nginx-1.2.4]# vim src/http/ngx_http_header_filter_module.c
#编辑该配置文件
static char ngx_http_server_string[] = "Server: ljz" CRLF;
#搜索“nginx”,定位到该行,然后更改其中原来的nginx为ljz,注意,这里必须和前一个配置文件中指定的名字一样
#更改完成后,保存退出即可
[root@nginx nginx-1.2.4]# vim src/http/ngx_http_special_response.c   #编辑此配置文件
static u_char ngx_http_error_tail[] =     #注意,有一段配置和这段内容非常相似,主要区分这一行即可
#如果改错了,在后面将会报错
"<hr><center>ljz</center>" CRLF    #将此行中间的nginx更改为ljz。
"</body>" CRLF
"</html>" CRLF
#更改完成后,保存退出即可
[root@nginx nginx-1.2.4]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module && make
#重新配置及编译
[root@nginx nginx-1.2.4]# mv /usr/local/nginx/sbin/nginx nginx2.bak   #将原有的nginx命令改名
[root@nginx nginx-1.2.4]# cp objs/nginx /usr/local/nginx/sbin/    #复制新生成的nginx命令到指定目录
[root@nginx nginx-1.2.4]# /usr/local/nginx/sbin/nginx -s stop    #停止nginx服务
[root@nginx nginx-1.2.4]# /usr/local/nginx/sbin/nginx     #启动nginx
[root@nginx nginx-1.2.4]# curl -I 127.0.0.1   #查看其头部信息
HTTP/1.1 200 OK
Server: ljz/666       #已经更改成功
    ...............#省略部分内容

V. Detailed nginx main configuration file location options

In nginx's master configuration file, there is a paragraph http {} in http {} also contains a server {}, in which a server {} represents a virtual host, which can be configured for a different web services parameters, said here about the detailed configuration of the location {}.

1, the role of the "=" of

"=" Sign indicates an absolute match, root access web pages can be accessed with arguments but not behind it, such as 127.0.0.1 can visit a success, but 127.0.0.1/html on the successful visit.

[root@nginx ~]# cd /usr/local/nginx/conf/    #切换至指定目录
[root@nginx conf]# vim nginx.conf          #编辑主配置文件
http {
    ...............#省略部分内容    
    server {
        listen       80;
       location = / {     #这里设置为“= /”
            root   test;
            index  index.html index.htm;
        }

    ...............#省略部分内容
    }
}
[root@nginx nginx]# ln -sf /usr/local/nginx/sbin/nginx /usr/local/sbin/
[root@nginx nginx]# nginx -t
[root@nginx nginx]# nginx -s reload    #多重载两次服务,否则可能不生效
[root@nginx nginx]# nginx -s reload
[root@nginx nginx]# mkdir test
[root@nginx nginx]# echo "`pwd`/test/index.html" > test/index.html
[root@nginx nginx]# cat test/index.html 
/usr/local/nginx/test/index.html

Client Access 192.168.20.5 test:
Build Nginx server and its configuration file Detailed

2, the difference between root and alias of

  • root: the file path is actually accessed will be spliced ​​into the path of the URL;
  • alias: the file path actually visit will not be spliced ​​URL path

In the following configuration, "^" indicates that begin with what, "~" to use a regular expression match

1) will now be in the configuration file location was changed to the following:

[root@nginx conf]# vim nginx.conf          #编辑主配置文件
http {
    ...............#省略部分内容    
    server {
        listen       80;
            location ^~ /www {
            root   /var/www/html;   #当访问127.0.0.1/www时,会寻找/var/www/html路径下的www目录
            index  index.html index.htm;
        }

    ...............#省略部分内容
    }
}
[root@nginx nginx]# nginx -t
[root@nginx nginx]# nginx -s reload    #多重载两次服务,否则可能不生效
[root@nginx nginx]# nginx -s reload
[root@nginx conf]# mkdir -p /var/www/html/www
[root@nginx conf]# echo "/var/www/html/www/index.html" > /var/www/html/www/index.html

Client Access 192.168.20.5/www test:
Build Nginx server and its configuration file Detailed

2) Now the configuration file to the following location:

[root@nginx conf]# vim nginx.conf          #编辑主配置文件
http {
    ...............#省略部分内容    
    server {
        listen       80;
          location ^~ /test02 {
            alias   /var/www/test02;   #访问127.0.0.1/test02会寻找/var/www/test02目录下的网页文件
            index  index.html index.htm;
        }

    ...............#省略部分内容
    }
}
[root@nginx nginx]# nginx -t
[root@nginx nginx]# nginx -s reload    
[root@nginx nginx]# nginx -s reload
[root@nginx conf]# mkdir -p /var/www/test02
[root@nginx conf]# echo "/var/www/test02/index.html" > /var/www/test02/index.html

Client Access 192.168.20.5/test02 test:
Build Nginx server and its configuration file Detailed

3, match the specified suffix, it is redirected to the specified file

[root@nginx conf]# vim nginx.conf          #编辑主配置文件
http {
    ...............#省略部分内容    
    server {
        listen       80;
             location ~* .(gif|jpg|png)$ {
            rewrite .(gif|jpg)$ /error.png;
        }
#以上表示当访问gif和jpg结尾的文件跳转到/usr/local/nginx/html/error.png
    ...............#省略部分内容
    }
}
[root@nginx nginx]# nginx -t
[root@nginx nginx]# nginx -s reload    
[root@nginx nginx]# nginx -s reload
[root@nginx html]# pwd    #查看当前路径
/usr/local/nginx/html
[root@nginx html]# ls    #error.png需存放在这个目录下
50x.html  error.png  index.html

Client Access 192.168.20.5/bb.gif test:

Build Nginx server and its configuration file Detailed

4, when the request matches the specified manner, the specific status code returned

[root@nginx conf]# vim nginx.conf          #编辑主配置文件
http {
    ...............#省略部分内容    
    server {
        listen       80;
          if ($request_method = TEST) {
            return 666;
        }
#当客户端以TEST的方式访问时,返回状态码666
    ...............#省略部分内容
    }
}
[root@nginx nginx]# nginx -t
[root@nginx nginx]# nginx -s reload    
[root@nginx nginx]# nginx -s reload

In this test machine execute the command curl -X TEST -I 127.0.0.1:

We can see the return of the specified status code
Build Nginx server and its configuration file Detailed

5, when the client is not accessible to specify the domain name, jump to a specific domain name

[root@nginx conf]# vim nginx.conf          #编辑主配置文件
http {
    ...............#省略部分内容    
    server {
        listen       80;
                if ($host != 'www.test.com'){
                           rewrite ^/(.*)$ https://www.baidu.com/$1;
                }
#以上表示当客户端不是通过www.test.com域名访问时,就跳转到百度首页
    ...............#省略部分内容
    }
}
[root@nginx nginx]# nginx -t
[root@nginx nginx]# nginx -s reload    
[root@nginx nginx]# nginx -s reload

Client Access 192.168.20.5 test:
Because before I shot, they visited once, so, when this input IP, will correspond to the auto and Baidu.
Build Nginx server and its configuration file Detailed

Sixth, Nginx configuration access https

We all know that port 80 http, https port 443, due to the more secure https, so now most web services are accessed through https way, then, to configure it to access https nginx server.

Because the Internet is a certified CA certificate need to pay for, so here to do one without the Internet certified CA certificate itself.

[root@nginx ca]# pwd     #切换至指定目录
/usr/local/nginx/ca
[root@nginx ca]# openssl genrsa -out ca.key 4096   #生成秘钥文件
[root@nginx ca]# openssl req -new -x509 -days 7304 -key ca.key -out ca.crt
#以下所有填写的内容,可直接按回车,接收默认值
             ..................#省略部分内容
Country Name (2 letter code) [XX]:zh       #国家名称
State or Province Name (full name) []:beijing         #州或省名(全称)
Locality Name (eg, city) [Default City]:beijing   #城市名称
Organization Name (eg, company) [Default Company Ltd]:test  #公司名称
Organizational Unit Name (eg, section) []:operation     #所在部门
Common Name (eg, your name or your server's hostname)    []:test.com  #主机名
Email Address []:[email protected]    #邮箱
[root@nginx ca]# ls      #确保当前目录下有下面两个文件
ca.crt  ca.key
[root@nginx ca]# vim /usr/local/nginx/conf/nginx.conf    #编辑主配置文件
             ..................#省略部分内容,搜索“HTTPS”定位到下面的配置项,并删除HTTPS下面server{ }所有的注释符号
#更改后如下(共修改两行即可):

    server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      /usr/local/nginx/ca/ca.crt;     #就改这一行,指定ca.crt的绝对路径
        ssl_certificate_key  /usr/local/nginx/ca/ca.key;     #再改这一行,指定ca.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;
        }
    }

}

#更改完成后,保存退出即可
[root@nginx ca]# nginx -s reload    #重启nginx
[root@nginx ca]# nginx -s reload

The client uses https to access the test (the Internet because the certificate has not been certified, it will appear the following warning message, click the "Advanced", you can choose to visit):
Build Nginx server and its configuration file Detailed

successful visit https:
Build Nginx server and its configuration file Detailed

-------- end of this article so far, thanks for reading --------

Guess you like

Origin blog.51cto.com/14154700/2443460