Nginx server set up and optimized depth

A, introduces Nginx
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, It is so, provide 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, it puts 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, 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
Nginx official Download: http://nginx.org/download/
Download I offer: https://pan.baidu.com/s/1PL0GyzRQ8zSPD74309R44g
Extraction Code: 4mt4
. 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 

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 services
in general in order 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 option
in nginx main configuration file, there is a passage of http {} in http {} also contains a server {}, wherein a server {} represents a virtual host, in which you can configure different parameters for a web service, said here about the location {} detailed configuration.
1, 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 matching
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:
Nginx server set up and optimized depth
2) Now the configuration file location was changed to the following:

[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:
Nginx server set up and optimized depth
2, match the specified suffix will be redirected to the specified file
demonstration a:

[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:
Nginx server set up and optimized depth
Demonstration II:

[root@nginx res]# pwd
/webroot/res
[root@nginx res]# ls             #该路径下存放的图片
test1.jpg
[root@nginx html]# pwd           #当前路径
/usr/local/nginx/html
[root@nginx html]# cat index.html       #有一个首页文件
/usr/local/nginx/html/index.html
[root@nginx html]# vim ../conf/nginx.conf          #编辑主配置文件
    server {
        listen       80;
        server_name  localhost;
        location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {     #“~”表示使用正则表达式,“ * ”表示不区分大小写
            root /webroot/res;  #当访问以以上gif、jpg等结尾的文件时,就去/webroot/res目录下找
            index index.html index.html;
                }
        location / {
            root   html;
            index  index.html index.htm;
        }
[root@nginx html]# nginx -s reload       #重启服务,使更改生效 

客户端访问Nginx的192.168.20.5进行测试:
Nginx server set up and optimized depth
看到的是html下的index.html文件的内容。现在访问192.168.20.5/test1.jpg进行测试:
Nginx server set up and optimized depth
这样,看到的就是/webroot/res/目录下的test1.jpg图片。
3、当匹配指定的请求方式,就返回特定的状态码

[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

在本机执行命令 curl -X TEST -I 127.0.0.1 进行测试:
可以看到返回了我们指定的状态码
Nginx server set up and optimized depth
4、当客户端不是以指定域名访问时,就跳转到指定的域名

[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

客户端访问192.168.20.5进行测试:
由于我在截图之前,就访问了一次,所以,这里输入IP时,自动会和百度对应上。
Nginx server set up and optimized depth
六、配置https访问Nginx
我们都知道http是80端口,https是443端口,由于https更加安全,所以现在大多数web服务都是通过https方式进行访问的,接下来,就配置一下https访问nginx服务器。

由于互联网认证的CA证书需要付费购买,所以这里就自己做一个,没有经过互联网认证的CA证书。

[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

客户端使用https访问测试(由于证书没有经过互联网认证的,所以会出现下面的警告信息,单击“高级”,选择继续访问即可):
Nginx server set up and optimized depth
https访问成功:
Nginx server set up and optimized depth
七、开启Nginx访问认证
有些时候,我们web服务的一些页面,不方便对所有人开放,这事,可以开启该网页的访问认证,开启后,就需要使用用户名密码进行登录,才可看到相应的页面。

没有开启访问认证的情况下访问我们192.168.20.5/auth/的网页文件,,可以直接访问,如下:
Nginx server set up and optimized depth
现在开启认证:

[root@nginx ~]# yum -y install httpd-tools       #安装所需htpasswd工具
[root@nginx ~]# htpasswd -c /usr/local/nginx/.passwd admin     #创建一个admin用户
New password:       #输入用户密码
Re-type new password:       #确认密码
#注:若要向.passwd中添加第二个用户,需要省略“-c”选项,否则会覆盖之前的所有用户。
Adding password for user admin
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf        #编辑Nginx配置文件
             ......................#省略部分内容,编辑需要开启认证的server配置段
 server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /auth {             #注意这里实际的路径相当于“/usr/local/nginx/html/auth”
            root   html;
            index  index.html index.htm;
            auth_basic "请输入登录账号";        #添加提示语句
            auth_basic_user_file /usr/local/nginx/.passwd;     #指定密码文件的存放路径
        }
#编辑完成后,保存退出即可
[root@nginx nginx]# nginx -s reload        #重启Nginx服务 

Client access test (you will be prompted to enter a user name and password, as long as .passwd file contains user and password, can log in):
Nginx server set up and optimized depth
After a successful login, you can see the page file:
Nginx server set up and optimized depth

Guess you like

Origin blog.51cto.com/14227204/2464167