nginx入门指南

2017-04-22  本文已影响0人  qianghaohao

Nginx入门指南

一.Nginx概述:

1.什么是Nginx?

Nginx(发音同engine x)是一个网页服务器,它能反向代理HTTP, HTTPS, SMTP, POP3, IMAP的协议链接,以及一个负载均衡器和一个HTTP缓存。
起初是供俄国大型的门户网站及搜索引擎Rambler(俄语:Рамблер)使用。此软件BSD-like协议下发行,可以在UNIX、GNU/Linux、BSD、Mac OS X、Solaris,以及Microsoft Windows等操作系统中运行。

2.Nginx的特点:

3.目前web服务器市场份额图:

4.正向代理和反向代理的区别:

二.安装Nginx:

1.准备工作:

在此下载Nginx最新版nginx-1.11.10:

wget http://nginx.org/download/nginx-1.11.10.tar.gz -O - | tar zxvf -

2.编译安装Nginx:

    sudo yum install -y openssl openssl-devel

运行以上命令后可以查看是否安装成功:


./configure --help

执行configure命令,添加一些定制化参数,并生成makefile:
     ./configure --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-debug 

相关参数说明:
--with-http_ssl_module: 使nginx支持SSL协议,提供HTTPS服务。
--with-http_stub_status_module:该模块可以让运行中的Nginx提供性能统计页面,获取相关的并发连接,请求信息。
--with-http_gzip_static_module:在做gzip压缩前,先查看相同位置是否有已经做过gzip压缩的.gz文件,如果有,就直接返回。
--with-debug:在nginx运行时通过修改配置文件来使其打印调试日志,这对于研究,定位nginx问题非常有帮助。
configure命令执行完后,会在源码目录生成Makefile文件和一个objs目录:
Makefile文件是指导make命令编译的脚本文件,objs目录存放编译过程中产生的二进制文件和一些configure产生的源代码文件。
现在nginx源码目录树如下(红框圈出来的味新生成的目录):


make
sudo make install

3.Nginx的使用:

/usr/local/nginx/sbin/nginx

这时,会读取默认路径下的配置文件:/usr/local/nginx/conf/nginx.conf

/usr/local/nginx/sbin/nginx -c path/nginx.conf

这时,会读取-c参数指定的配置文件来启动Nginx。

/usr/local/nginx/sbin/nginx -g "pid /var/nginx/test.pid;"

上面的命令意味着会把pid文件写入到/var/nginx/test.pid中。

/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -t -q

测试配置选项是时,使用-q参数可以不把error级别以下的信息输出到屏幕。

/usr/local/nginx/sbin/nginx -v
/usr/local/nginx/sbin/nginx -V

-V参数除了可以显示Nginx的版本信息外,还可以显示配置编译阶段的信息,如gcc编译器版本,操作系统版本,执行configure时的参数等。

/usr/local/nginx/sbin/nginx -s stop

使用-s stop可以强制停止Nginx服务。-s参数其实是告诉Nginx程序向正在运行的Nginx服务发送信号,Nginx程序通过nginx.pid文件得到master进程的ID,再向运行中的master进程发送TERM信号来快速地关闭Nginx服务。
同样可以给master进程发送TERM或者INT信号来快速停止:

kill -s SIGTERM NginxMasterPid
kill -s SIGINT NginxMasterPid
/usr/local/nginx/sbin/nginx -s quit

如果希望Nginx服务可以正常地处理完当前前所有请求再停止服务,那么可以使用-s quit参数来停止服务。这种方式首先会关闭监听端口,停止接收新的连接,然后把当前正则处理的连接全部处理完,最后再退出进程。
同样可以发送信号的方式优雅地停止服务:

kill -s SIGQUIT NginxMasterPid

优雅地停止某个worker进程:

kill -s SIGWINCH NginxWorkerPid
/usr/local/nginx/sbin/nginx -s reload

同样可以通过kill发送信号来达到同样的效果:

  kill -s SIGHUP NginxMasterPid

二.Nginx的配置:

1.运行中的Nginx进程间的关系:

在正式提供服务的产品环境下,部署Nginx时都是使用一个master进程来管理多个worker进程,一般情况下,worker进程的数量与服务器上的CPU核心数相等。每一个worker进程都是繁忙的,他们真正地提供互联网服务,master进程则很"清闲",只负责监控管理worker进程。部署后的Nginx进程间的关系如图下图所示:


2.Nginx配置中的通用语法:

Nginx的配置文件其实是一个普通的文本文件。下面来看一个简单的例子:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # 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;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # 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;
    #    }
    #}

}

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

上面代码段中的events,http,server,location都是块配置项。块配置项可以嵌套,内层块直接继承外层块,例如,上例中server块里的任意配置都是基于http块里的已有配置的。当内外层中的配置发生冲突时,究竟是以内层块还是外层块的配置为准,取决于解析这个配置项的模块。

    log_format main '$time_local|10.4.24.116|$request|$status|'
                                                    '$remote_user|$remote_addr|$http_user_agent|$http_referer|$host|'
                                                    '$bytes_sent|$request_time|$upstream_response_time|$upstream_addr|'
                                                    '$connection|$connection_requests|$upstream_http_content_type|$upstream_http_content_disposition';

其中变量前要加$符号。需要注意的是,这种变量只有少数模块支持,并不是通用的。
注意⚠️ :
在执行configure命令时,我们已经把许多模块编译进Nginx中,但是否启用这些模块,一般取决于配置文件中相应的配置项。换句话说,每个Nginx模块都有自己感兴趣的配置项,大部分模块都必须在nginx.conf中读取某个配置项后才会在运行时启动。例如,只有当配置http{...}这个配置项时,ngx_http_module模块才会在Nginx中启用,其他依赖ngx_http_module的模块才能正常使用。

3.一个静态Web服务器常用的配置:

静态Web服务器的主要功能由ngx_http_core_module模块(HTTP框架的主要成员)实现,当然,一个完整的静态Web服务器还有许多功能是由其他的HTTP模块实现的。一个典型的静态Web服务器还会包含多个server块和location块,例如:

user  web;
worker_processes  6;

#error_log  logs/error.log;
error_log  logs/error.log  info;
#error_log  logs/error.log  info;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;


    log_format main '$time_local|10.4.24.116|$request|$status|'
                    '$remote_user|$remote_addr|$http_user_agent|$http_referer|$host|'
                    '$bytes_sent|$request_time|$upstream_response_time|$upstream_addr|'
                    '$connection|$connection_requests|$upstream_http_content_type|$upstream_http_content_disposition';
    
    access_log  logs/access.log  main;

    sendfile        on;
    tcp_nodelay     on;
    #tcp_nopush     on;

    keepalive_timeout  120 100;
    resolver_timeout   15;
    client_body_timeout        20;
    client_header_timeout      20;
    client_body_buffer_size 512k;

    large_client_header_buffers 1 512k;
    #gzip  on;
    
    #APP
    include server/zapier.chime.me.conf;
    include server/https_app116.chime.me.conf;
    include server/http_app116.chime.me.conf;
    #CRM 
    include server/https_test.chime.me.conf;
    include server/https_dev.chime.me.conf;
    include server/https_dev2.chime.me.conf;
    include server/https_static.chime.me.conf;
    include server/crmnginx.chime.me.conf;
    include server/brokernginx.chime.me.conf;

    include server/http_oldlender.chime.me.conf;

    include server/frontend.chime.me.conf;
    include server/chime.me.conf;
    include server/twilio.chime.me.conf;

    include server/http_testzillow.chime.me.conf; 

    #agnet 资历收集页图片地址 
    include server/uploadfile.conf;
    
    #测试nginx status
    server {
        listen *:80 ;
        server_name localhost status.chime.me;
        
        location /ngx_status {
            stub_status on;
            access_log off;
            allow 10.2.204.166;
            deny all;
        }
    }
}

所有的HTTP配置项必须直属于http块,location块,upstream块或if块。
Web服务器常用配置项:

   location /download/ {
       root /opt/web/html/;
   }

在上面配置中,如果有一个请求的URI是/download/index/test.html,那么web服务器将会返回服务器上/opt/web/html/download/index/test.html

     location / {
        root path;
        index /index.html /html/inde.php /index.php
     }

接受到请求后,Nginx首先会尝试访问path/index.php文件,如果可以访问,就直接返回文件内容结束请求,否则再试图返回path/html/index.php的内容,依此类推。

4.配置一个静态web服务器:

nginx的默认配置就是一个静态web服务器,启动后可以直接访问,配置文件如下:

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

5.给Nginx的access log添加唯一的request id字段:

wget http://mirror.centos.org/centos/7/os/x86_64/Packages/uuid-perl-1.6.2-26.el7.x86_64.rpm
yum install uuid-perl-1.6.2-26.el7.x86_64.rpm
 sudo yum install -y perl-devel perl-ExtUtils-Embed

然后配置编译参数,执行configure生成makfile:

 ./configure --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-debug --with-http_perl_module
 sbin/nginx -s reload
    /**     * 添加用户perference信息     * @param userPreference     */    UserPreference andUserPreference(UserPreference userPreference);    /**     * 获取用户preference页面信息     * @param userId     * @return     */    UserPreference getUserPreference(long userId);    /**     * 更新时区标识     * @param userId     * @param timezoneId     */    void updateTimezoneId(long userId, String timezoneId);    /**     * 更新是否接受lead开关状态     * @param userId     * @param sendLeadFlag     */    void updateSendLeadFlag(long userId, boolean sendLeadFlag);
上一篇 下一篇

猜你喜欢

热点阅读