NGINX2,


nginx(二) nginx编译安装 及 配置WEB服务

       在前面《nginx详解》文章中,我们对nginx有了一个基本的认识:包括应用场景、nginx基本架构、功能特性、并发模型以及配置说明等,我们知道nginx应用比较多的场景是WEB服务器和反向代理服务器。

       下面将先进行nginx编译安装,然后再进行nginx的WEB服务相关的应用配置:包括设置配置文件vim下语法高亮显示、配置虚拟主机、基于IP的访问控制、基于用户认证的访问控制、建立下载站点下载列表、URL地址重写/重定向、防盗链、提供Nginx状态页面、配置gzip压缩、日志、基于SSL提供https服务等。

1、配置环境准备

1、WEB服务器:

主机系统:CentOS 6.4 x86_64;

IP:192.168.18.242 (host name:node2.tjiyu.com);

2、Client端:

IP:192.168.18.245;

一般浏览器;

2、下载编译安装

       去nginx官网上把最新稳定版本的源码包下载下来,我们这里使用nginx-1.10.2版本;然后把源码包放到我们操作的主机上,下面开始编译安装。

2-1、解压,创建软连接

[plain] view plain copy
  1. [root@node2 ~]# tar xf nginx-1.10.2.tar.gz  
  2.   
  3. [root@node2 ~]# ln -sv nginx-1.10.2 nginx  
  4.   
  5. [root@node2 ~]# cd nginx  
  6.   
  7. [root@node2 nginx]# ll  

2-2、安装编译开发工具类库

       用yum安装、更新开发工具"Development Tools"和"Server Platform Deveopment",而nginx会依赖openssl-devel和pcre-devel类库,安装如下:

[plain] view plain copy
  1. [root@node2 nginx]# yum groupinstall "Development Tools" "Server Platform Deveopment"  
  2.   
  3. [root@node2 ~]# yum install openssl-devel pcre-devel  

2-3、创建用户和用户组

       分别创建名为"nginx"的用户和组,用来运行nginx的worker进程,操作如下:

[plain] view plain copy
  1. [root@node2 nginx]# groupadd -r nginx  
  2.   
  3. [root@node2 nginx]# useradd -r -g nginx nginx  

2-4、编译并安装

       先configure指定编译选项,如安装目录、上面创建的运行用户、需要的扩展模块(SSL、FastCGI)等,选项及参数说明:http://nginx.org/en/docs/configure.html,操作如下:

[plain] view plain copy
  1. [root@node2 nginx]# ./configure \  
  2.   
  3.     --prefix=/usr \  
  4.   
  5.     --sbin-path=/usr/sbin/nginx \  
  6.   
  7.     --conf-path=/etc/nginx/nginx.conf \  
  8.   
  9.     --error-log-path=/var/log/nginx/error.log \  
  10.   
  11.     --http-log-path=/var/log/nginx/access.log \  
  12.   
  13.     --pid-path=/var/run/nginx/nginx.pid \  
  14.   
  15.     --lock-path=/var/lock/nginx.lock \  
  16.   
  17.     --user=nginx \  
  18.   
  19.     --group=nginx \  
  20.   
  21.     --with-http_ssl_module \  
  22.   
  23.     --with-http_flv_module \  
  24.   
  25.     --with-http_stub_status_module \  
  26.   
  27.     --with-http_gzip_static_module \  
  28.   
  29.     --http-client-body-temp-path=/var/tmp/nginx/client/ \  
  30.   
  31.     --http-proxy-temp-path=/var/tmp/nginx/proxy/ \  
  32.   
  33.     --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \  
  34.   
  35.     --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \  
  36.   
  37.     --http-scgi-temp-path=/var/tmp/nginx/scgi \  
  38.   
  39.     --with-pcre  

       Configure成功如下:

       接着开始编译并安装,如下:

[plain] view plain copy
  1. [root@node2 nginx]# make && make install  

2-5、为nginx提供SysV init服务脚本

       先创建/etc/init.d/nginx服务脚本,这基于ngInx自身提供的命令实现的,脚本内容如下:

[plain] view plain copy
  1. #!/bin/sh  
  2.   
  3. #  
  4.   
  5. # nginx - this script starts and stops the nginx daemon  
  6.   
  7. #  
  8.   
  9. # chkconfig: - 85 15  
  10.   
  11. # description: Nginx is an HTTP(S) server, HTTP(S) reverse \  
  12.   
  13. # proxy and IMAP/POP3 proxy server  
  14.   
  15. # processname: nginx  
  16.   
  17. # config: /etc/nginx/nginx.conf  
  18.   
  19. # config: /etc/sysconfig/nginx  
  20.   
  21. # pidfile: /var/run/nginx.pid  
  22.   
  23.    
  24.   
  25. # Source function library.  
  26.   
  27. . /etc/rc.d/init.d/functions  
  28.   
  29.    
  30.   
  31. # Source networking configuration.  
  32.   
  33. . /etc/sysconfig/network  
  34.   
  35.    
  36.   
  37. # Check that networking is up.  
  38.   
  39. [ "$NETWORKING" = "no" ] && exit 0  
  40.   
  41.    
  42.   
  43. nginx="/usr/sbin/nginx"  
  44.   
  45. prog=$(basename $nginx)  
  46.   
  47.    
  48.   
  49. NGINX_CONF_FILE="/etc/nginx/nginx.conf"  
  50.   
  51.    
  52.   
  53. [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx  
  54.   
  55.    
  56.   
  57. lockfile=/var/lock/subsys/nginx  
  58.   
  59.    
  60.   
  61. make_dirs() {  
  62.   
  63.     # make required directories  
  64.   
  65.     user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=[][]∗.*/\1/g' -`  
  66.   
  67.     options=`$nginx -V 2>&1 | grep 'configure arguments:'`  
  68.   
  69.     for opt in $options; do  
  70.   
  71.         if [ `echo $opt | grep '.*-temp-path'` ]; then  
  72.   
  73.             value=`echo $opt | cut -d "=" -f 2`  
  74.   
  75.             if [ ! -d "$value" ]; then  
  76.   
  77.                 # echo "creating" $value  
  78.   
  79.                 mkdir -p $value && chown -R $user $value   
  80.   
  81.             fi   
  82.   
  83.         fi   
  84.   
  85.     done   
  86.   
  87. }  
  88.   
  89. start() {  
  90.   
  91.     [ -x $nginx ] || exit 5  
  92.   
  93.     [ -f $NGINX_CONF_FILE ] || exit 6  
  94.   
  95.     make_dirs  
  96.   
  97.     echo -n $"Starting $prog: "  
  98.   
  99.     daemon $nginx -c $NGINX_CONF_FILE  
  100.   
  101.     retval=$?  
  102.   
  103.     echo  
  104.   
  105.     [ $retval -eq 0 ] && touch $lockfile  
  106.   
  107.     return $retval   
  108.   
  109. }  
  110.   
  111. stop() {  
  112.   
  113.     echo -n $"Stopping $prog: "  
  114.   
  115.     killproc $prog -QUIT  
  116.   
  117.     retval=$?  
  118.   
  119.     echo  
  120.   
  121.     [ $retval -eq 0 ] && rm -f $lockfile  
  122.   
  123.     return $retval   
  124.   
  125. }  
  126.   
  127. restart() {  
  128.   
  129.     configtest || return $?  
  130.   
  131.     stop  
  132.   
  133.     sleep 1  
  134.   
  135.     start   
  136.   
  137. }  
  138.   
  139. reload() {  
  140.   
  141.     configtest || return $?  
  142.   
  143.     echo -n $"Reloading $prog: "  
  144.   
  145.     killproc $nginx -HUP  
  146.   
  147.     RETVAL=$?  
  148.   
  149.     echo   
  150.   
  151. }  
  152.   
  153. force_reload() {  
  154.   
  155.     restart   
  156.   
  157. }  
  158.   
  159. configtest() {  
  160.   
  161.     $nginx -t -c $NGINX_CONF_FILE   
  162.   
  163. }  
  164.   
  165. rh_status() {  
  166.   
  167.     status $prog   
  168.   
  169. }  
  170.   
  171. rh_status_q() {  
  172.   
  173.     rh_status >/dev/null 2>&1   
  174.   
  175. }  
  176.   
  177. case "$1" in  
  178.   
  179. start)  
  180.   
  181.     rh_status_q && exit 0  
  182.   
  183.     $1  
  184.   
  185.     ;;   
  186.   
  187. stop)  
  188.   
  189.     rh_status_q || exit 0  
  190.   
  191.     $1  
  192.   
  193.     ;;   
  194.   
  195. restart|configtest)  
  196.   
  197.     $1   
  198.   
  199.     ;;   
  200.   
  201. reload)  
  202.   
  203.     rh_status_q || exit 7  
  204.   
  205.     $1  
  206.   
  207.     ;;   
  208.   
  209. force-reload)  
  210.   
  211.     force_reload  
  212.   
  213.     ;;   
  214.   
  215. status)  
  216.   
  217.     rh_status  
  218.   
  219.     ;;   
  220.   
  221. condrestart|try-restart)  
  222.   
  223.     rh_status_q || exit 0  
  224.   
  225.     ;;   
  226.   
  227. *)  
  228.   
  229. echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"  
  230.   
  231. exit 2  
  232.   
  233. esac  

       并为此脚本赋予执行权限,然后添加到系统服务管理列表,并让其开机自动启动,操作如下:

[plain] view plain copy
  1. [root@node2 nginx]# vim /etc/init.d/nginx  
  2.   
  3. [root@node2 nginx]# chmod +x /etc/init.d/nginx  
  4.   
  5. [root@node2 nginx]# chkconfig --add nginx  
  6.   
  7. [root@node2 nginx]# chkconfig nginx on  
  8.   
  9. [root@node2 nginx]# chkconfig --list nginx  

2-6、启动并访问测试

       启动nginx,我们看到因为httpd占用80端口而失败,关闭httpd后再启动nginx正常;查看网络状态,可以看到nginx正在监听80端口;用测试主机访问nginx主机的IP,可以看到nginx的欢迎页面,过程如下:

[plain] view plain copy
  1. [root@node2 nginx]# service nginx start  
  2.   
  3. [root@node2 nginx]# netstat -ntulp | grep nginx  

3、配置Nginx

      前面编译nginx的时候,我们用选项--conf-path=/etc/nginx/nginx.conf(默认也是这个目录),指定的了配置文件及所在目录,所以我们到/etc/nginx/下可以看到nginx.conf配置文件,而.default结尾的是nginx默认编译选项的配置文件,已经没有意义了。

      前面《nginx详解》我们已经详细分析说明nginx配置文件的几个配置区域块和大部分的配置选项,下面就不一一说明了,只说明一些用到的配置选项。

3-1、设置配置文件vim下语法高亮显示

      linux系统下vim或者vi编辑器默认是没有对nginx配置的语法高亮设置。但是我们可以到http://www.vim.org/scripts/script.php?script_id=1886下载nginx.vim,然后根据它上面的说明,进行简单的配置,如下:

[plain] view plain copy
  1. [root@node2 ~]# mkdir .vim/syntax -pv  
  2.   
  3. [root@node2 ~]# cd .vim/syntax/  
  4.   
  5. [root@node2 syntax]# mv ~/nginx.vim ./  
  6.   
  7. [root@node2 syntax]# ls  
  8.   
  9. nginx.vim  
  10.   
  11. [root@node2 syntax]# cd ..  
  12.   
  13. [root@node2 .vim]# vim filetype.vim  
  14.   
  15. [root@node2 .vim]# cat filetype.vim  
  16.   
  17. au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* if &ft == '' | setfiletype nginx | endif  
  18.   
  19. [root@node2 .vim]# vim /etc/nginx/nginx.conf  

3-2、配置虚拟主机

      编辑nginx.conf,配置两个虚拟主机www.tjiyu.com和www.test.com,资源文件目录分别/data/tjiyu和/data/test,可以看到最简单的配置只需要三行,操作如下:

[plain] view plain copy
  1. [root@node2 nginx]# cp nginx.conf nginx.conf.bak  
  2.   
  3. [root@node2 nginx]# vim nginx.conf  
[plain] view plain copy
  1. server {  
  2.   
  3.     listen 80;  
  4.   
  5.     server_name www.tjiyu.com;  
  6.   
  7.     location / {  
  8.   
  9.     root /data/tjiyu;  
  10.   
  11.     index index.html index.htm;  
  12.   
  13.     }  
  14.   
  15. }  
  16.   
  17. server {  
  18.   
  19.     listen 80 default_server;    #配置默认虚拟主机  
  20.   
  21.     server_name www.test.com;  
  22.   
  23.     root /data/test;  
  24.   
  25. }  

      然后分别创建资源目录,提供index.html测试页面,然后使nginx重新加载配置,操作如下:

[plain] view plain copy
  1. [root@node2 nginx]# mkdir /data  
  2.   
  3. [root@node2 nginx]# mkdir /data/tjiyu  
  4.   
  5. [root@node2 nginx]# echo "<h1>www.tjiyu.com</h1>" > /data/tjiyu/index.html  
  6.   
  7. [root@node2 nginx]# mkdir /data/test  
  8.   
  9. [root@node2 nginx]# echo "<h1>www.test.com</h1>" >  
  10.   
  11. [root@node2 nginx]# service nginx reload  

      在我们的测试主机上配置hosts,让访问虚拟主机名可以指向主机IP,win7 x86_64上C:\Windows\System32\drivers\etc\HOSTS添加如下两行记录,如上:

[plain] view plain copy
  1. 192.168.18.242    www.tjiyu.com  
  2.   
  3. 192.168.18.242 www.test.com  

      然后访问两个访问虚拟主机,可以看到提供的测试页面;因为我们在www.test.com的listen选项配置了default_server,所以直接访问主机IP是返回的是该虚拟主机的页面,如下:

3-3、基于IP的访问控制

      基于IP的访问控制是ngx_http_access_module模块的功能,只有允许选项allow和禁止选项deny。

      配置第二台虚拟主机只允许的192.168.18.*网段内的主机访问,但除测试主机192.168.18.244外,注意,多个规则是自上而下进行匹配的,所以不允许测试主机访问得在最上面;测试访问www.test.com可以看到返回403禁止访问页面,而访问www.tjiyu.com是正常的,过程如下:

[plain] view plain copy
  1. [root@node2 nginx]# vim nginx.conf  
  2.   
  3. root@node2 nginx]# service nginx reload  

[plain] view plain copy
  1. server {  
  2.   
  3.    listen 80 default_server;  
  4.   
  5.    server_name www.test.com;  
  6.   
  7.    root /data/test;  
  8.   
  9.       
  10.   
  11.    deny 192.168.18.244;    #不允许测试主机访问  
  12.   
  13.    allow 192.168.18.0/24;    #只允许的192.168.18.*网段内的主机访问  
  14.   
  15.    deny all;                #不允许其他所有外网访问  

3-4、基于用户认证的访问控制

      基于用户认证的访问控制是ngx_http_auth_basic_module模块的功能,只有配置名称(或者off)选项auth_basic和配置文件选项auth_basic_user_file,文件由htpasswd生成,包括用户和密码。

      先创建需要用户认证的目录/data/test/admin,提供一个测试页面;然后用htpasswd生成认证文件;编辑配置文件,用location匹配/data/test/admin目录,接着在里面配置访问控制配置的名称字符串和访问控制配置的文件,过程如下:

[plain] view plain copy
  1.  [root@node2 nginx]# mkdir /data/test/admin  
  2.   
  3. [root@node2 nginx]# echo "<h1>admin area</h1>" > /data/test/admin/index.html  
  4.   
  5. [root@node2 nginx]# htpasswd -c -m /etc/nginx/.htpasswd admin  
  6.   
  7. [root@node2 nginx]# vim nginx.conf  
  8.   
  9. [root@node2 nginx]# service nginx reload  
[plain] view plain copy
  1. server {  
  2.   
  3.     listen 80 default_server; #配置默认虚拟主机  
  4.   
  5.     server_name www.test.com; #配置虚拟主机名  
  6.   
  7.     root /data/test; #配置资源文件根目录  
  8.   
  9.        
  10.   
  11.     #deny 192.168.18.244; #不允许测试主机访问  
  12.   
  13.     allow 192.168.18.0/24; #只允许的192.168.18.*网段内的主机访问  
  14.   
  15.     deny all; #不允许其他所有外网访问  
  16.   
  17.        
  18.   
  19.     location /admin/ { #匹配基于用户认证的访问控制  
  20.   
  21.         auth_basic "admin area"; #访问控制配置的名称字符串,或者off关闭  
  22.   
  23.         auth_basic_user_file /etc/nginx/.htpasswd; #访问控制配置的文件,htpasswd生成,包含用户名用密码  
  24.   
  25.     }  
  26.   
  27. }   

      测试访问www.test.com正常,访问www.test.com/admin/需要用户和密码认证,也就实现了目录/data/test/admin里的资源需要用户认证,如下:

3-5、建立下载站点下载列表

      下载站点下载列表是ngx_http_autoindex_module模块的功能,有几个选项,最基本就是开关选项autoindex on | off和显示时间选项autoindex_localtime on | off。

      先创建存放下载资源的目录/data/test/download,复制一些文件进去提供测试;然后编辑配置文件,用location匹配/data/test/download目录,接着在里面配置打开下载列表功能;测试访问www.test.com/download可以看到下载列表,过程如下:

[plain] view plain copy
  1.  [root@node2 nginx]# mkdir /data/test/download  
  2.   
  3. [root@node2 nginx]# cp /etc/nginx/* /data/test/download/  
  4.   
  5. [root@node2 nginx]# vim nginx.conf  
  6.   
  7. [root@node2 nginx]# service nginx reload  
[plain] view plain copy
  1. server {  
  2.   
  3.     listen 80 default_server;  
  4.   
  5.     server_name www.test.com;  
  6.   
  7.     root /data/test;  
  8.   
  9.        
  10.   
  11.     location /download/ {  
  12.   
  13.         autoindex on; #打开下载列表功能  
  14.   
  15.         autoindex_localtime on; #显示时间  
  16.   
  17.     }   
  18.   
  19. }  

3-6、URL地址重写/重定向

      URL地址重写/重定向是ngx_http_rewrite_module模块的功能,通过正则匹配,把匹配的URL重写为指定的URL,以重写的URL来请求响应。主要应用在实现URL跳转、域名跳转、站点镜像等,比如网站改版,目录结构发生改变,但不希望不改变页面中的URL,用URL地址重写来实现。

1、if和rewrite选项

      这里有两个比较重要的选项,if和rewrite:If在上面已经介绍过了,在很多地方都用到,这里用于检测条件是否成立;而rewrite regex replacement [flag],匹配regex正则表达式(可以省略,直接重写),以replacement重写代替,flag为标志位,主要有:

[plain] view plain copy
  1. last:一旦被当前规则匹配并重写后立即停止检查后续饿的其他rewrite的规则,而后通过重写后的规则重新发起请求;  
  2.   
  3. break:一旦被当前规则匹配并重写后立即停止检查后续饿的其他rewrite的规则,而后继续由nginx进行后续的操作;  
  4.   
  5. redirect:返回302临时重定向代码;  
  6.   
  7. permanent:返回301永久重定向;  

      注意:当有多个rewrite规则一起使用时,可能会循环匹配,nginx最多循环10次,超出之后返回500错误;一般将rewrite写在location中时都使用break标志,或者将rewrite写if上下文中。

2、配置

      配置www.test.com虚拟主机的当目录$root_dir/images改为$root_dir /imgs时,可以通过URL重写,让www.test.com/images/*请求还能和原来一样,不过实际变为了www.test.com/imgs/*。

      直接创建/data/test/imgs目录,放一些图片文件进去用来测试;然后配置文件;测试访问www.test.com/images/2.jpg可以正常看到刚才放到/data/test/imgs图片,过程如下:

[plain] view plain copy
  1. [root@node2 nginx]# mkdir /data/test/imgs  
  2.   
  3. [root@node2 nginx]# mv /root/*.jpg /data/test/imgs/  
  4.   
  5. [root@node2 nginx]# ls /data/test/imgs/  
  6.   
  7. [root@node2 nginx]# vim nginx.conf  
  8.   
  9. [root@node2 nginx]# service nginx reload  
[plain] view plain copy
  1. server {  
  2.   
  3.     listen 80 default_server;  
  4.   
  5.     server_name www.test.com;  
  6.   
  7.     root /data/test;  
  8.   
  9.     location /images/ {  
  10.   
  11.         rewrite ^/images/(.*)$ /imgs/$1 break; #URL重写:让www.test.com/images/*请求还能和原来一样,不>过实际变为了www.test.com/imgs/*  
  12.   
  13.     }  
  14.   
  15. }  

3-7、防盗链

      防盗链基于是ngx_http_referer_module模块的功能,主要通过请求头部"Referer"字段识别,配置有两点:

(1)valid_referers选项,定义合规引用

[plain] view plain copy
  1. valid_referers none |blocked |server_names|string ...  
  2.   
  3. none表示没有"Referer",blocked表示 "Referer" 没有没有以"http://"或"https://"开头;  

(2)($invaild_referer变量,判断不合规的引用,返回一个提示

[plain] view plain copy
  1. if ($invaild_referer) {  
  2.   
  3.         rewrite ^/.*$ http://www.a.com/403.html  
  4.   
  5. }  

      下面配置当www.tjiyu.com虚拟主机页面引用www.test.com虚拟主机上的图片时,返回一个"图片仅供内部交流使用的图片"。www.test.com虚拟主机上配置location匹配图片文件,valid_referers定义合规引用,包括自己的虚拟主机名称等,然后if ($invaild_referer)判断不合规的引用,用URL地址重写返回一个提示图片,操作配置如下:

[plain] view plain copy
  1. [root@node2 nginx]# vim nginx.conf  

[plain] view plain copy
  1. location ~* \.(jpg|gif|jpeg|png)$ { #匹配图片文件请求  
  2.   
  3.     valid_referers none blocked www.test.com *.test.com; #定义合规引用,包括自己站主机等  
  4.   
  5.     if ($invalid_referer) {  
  6.   
  7.         rewrite ^/ http://www.test.com/imgs/a.jpg; #判断不合规的引用,用URL地址重写返回一个提示>图片  
  8.   
  9.     }  
  10.   
  11. }  

      然后在www.tjiyu.com虚拟主机测试页面加入图片引用,测试访问www.tjiyu.com可以看到引用的http://www.test.com/imgs/1.jpg,但返回的是我们配置http://www.test.com/imgs/a.jpg,过程如下:

[plain] view plain copy
  1. [root@node2 nginx]# vim /data/tjiyu/index.html  
  2.   
  3. [root@node2 nginx]# service nginx reload  

[plain] view plain copy
  1. <img src="http://www.test.com/imgs/1.jpg">  

3-8、提供Nginx状态页面

      提供Nginx状态页面指的是ngx_http_stub_status_module模块的功能,还有一个可以提供更详细信息的ngx_http_status_module模块,配置都很简单,不过编译nginx时需要指定包含进来。

      可以看到的信息有:

当下处于活动状态的总数;

接受的总数,已经建立和处理总数,请求的总数;

正在接受的并发请求个数,正在读取的个数或发往客户端的,长连接中的处于活动状态的值;

      配置一个location匹配访问,里面"stub_status;"就可以打开状态页面功能,注意1.7.5版本前需要"stub_status on;",然后加入用户认证和不记录日志,以防信息泄露,过程如下:

[plain] view plain copy
  1. [root@node2 nginx]# vim nginx.conf  
  2.   
  3. [root@node2 nginx]# service nginx reload  
[plain] view plain copy
  1. location /stub_status {  
  2.   
  3.     stub_status; #打开状态页面功能  
  4.   
  5.     auth_basic "stub_status"; #访问控制配置的名称字符串,或者off关闭  
  6.   
  7.     auth_basic_user_file /etc/nginx/.htpasswd; #访问控制配置的文件,htpasswd生成,包含用户名用密码  
  8.   
  9.     access_log off; #访问不记录日志  
  10.   
  11. }  

3-9、配置gzip压缩

      提供gzip压缩指的是ngx_http_gzip_module模块的功能,nginx默认会附带gzip压缩的功能,而ngx_http_gzip_static_module模块是提供gzip预压缩功能,需要编译指定。

配置选项有:

[plain] view plain copy
  1. gzip on|off  
  2.   
  3. gzip_buffer 使用的缓存大小  
  4.   
  5. gzip_comp_level 压缩的级别  
  6.   
  7. gzip_disable 不压缩的类型或浏览器  
  8.   
  9. gzip_min_length 最少压缩的大小  
  10.   
  11. gzip_http_version 压缩完成以后发送http的版本  
  12.   
  13. gzip_types:只压缩的格式  

      nginx将响应报文发送至客户端之前可以启用压缩功能,这能够有效地节约带宽,并提高响应至客户端的速度。可以在http块或server块中配置,一般在http块中配置,配置如下:

[plain] view plain copy
  1.  gzip on; #打开gzip压缩功能  
  2.   
  3. gzip_http_version 1.0; #使用1.0版本  
  4.   
  5. gzip_comp_level 4; #压缩级别为4  
  6.   
  7. gzip_min_length 64; #内容超过最少长度后才开启压缩:64k gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript application/json; #压缩的文件类型:文本压  
  8.   
  9. gzip_disable msie6; #不压缩的浏览器类型:ie6不支持  

3-10、配置日志

      Nginx常用的日志分为:错误日志error_log,这是nginx核心模块ngx_core_module提供的,前面《nginx详解》已有详细的说明;http访问日志access_log,这是ngx_http_log_module模块提供的。

      这两种日志默认都是打开记录的,而我们configure配置编译的时候已经指定了日志存放的目录,我们可以看到目录下已经存在这两个日志文件,如下:

      下面就来配置http访问日志,配置选项有:

[plain] view plain copy
  1. access_log off | path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]]; #设置存放路径、(引用)日志格式、缓存区大小、压缩等级、缓存时间等;  
  2.   
  3. log_format name string ...; #定义日志格式,access_log引用  
  4.   
  5. open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time]; #设置日志文件缓存  

      注意,默认access_log logs/access.log combined; log_format combined "...";也就是说日志格式为combined,如下:

[plain] view plain copy
  1. log_format combined '$remote_addr - $remote_user [$time_local] '  
  2.   
  3.     '"$request" $status $body_bytes_sent '  
  4.   
  5.     '"$http_referer" "$http_user_agent"';  

      格式定义中可以使用公共变量和仅日志格式中的变量。

      典型应用配置:如果请求经过nginx反向代理服务器,后端web服务器无法直接获取到客户端真实的IP地址(因为$remote_addr获取到的是反向代理IP地址)。可以配置反向代理服务器在转发请求的http头信息中增加"x-Forwarded-For"行信息,该信息中记录客户端IP地址和客户端请求的服务器地址;而后在后端服务器就配置重新定义日志格式,增加"$http_x_forwarded_for"变量信息到格式,就如原来配置文件中存在的配置(已注释,后面介绍nginx负载均衡再配置),如下:

3-11、配置基于SSL提供https服务

      提供基于SSL提供https服务的是ngx_mail_ssl_module模块,需要编译指定。

1、创建CA自签证书

[plain] view plain copy
  1. [root@node2 ~]# cd /etc/pki/CA/  
  2.   
  3. [root@node2 CA]# ls  
  4.   
  5. certs crl newcerts private  
  6.   
  7. [root@node2 CA]# cd private/  
  8.   
  9. [root@node2 private]# ls  
  10.   
  11. [root@node2 private]# (umask 077; openssl genrsa 2048 > cakey.pem)  
  12.   
  13.     Generating RSA private key, 2048 bit long modulus  
  14.   
  15.     ....+++  
  16.   
  17.     ..........................................................+++  
  18.   
  19.     e is 65537 (0x10001)  
  20.   
  21.     [root@node2 private]# openssl req -new -x509 -key ./cakey.pem -out ../cacert.pem  
  22.   
  23.     You are about to be asked to enter information that will be incorporated  
  24.   
  25.     into your certificate request.  
  26.   
  27.     What you are about to enter is what is called a Distinguished Name or a DN.  
  28.   
  29.     There are quite a few fields but you can leave some blank  
  30.   
  31.     For some fields there will be a default value,  
  32.   
  33.     If you enter '.', the field will be left blank.  
  34.   
  35.     -----  
  36.   
  37.     Country Name (2 letter code) [XX]:CN  
  38.   
  39.     State or Province Name (full name) []:HZ  
  40.   
  41.     Locality Name (eg, city) [Default City]:ZJ  
  42.   
  43.     Organization Name (eg, company) [Default Company Ltd]:TJIYU  
  44.   
  45.     Organizational Unit Name (eg, section) []:TEST  
  46.   
  47.     Common Name (eg, your name or your server's hostname) []:ca.tjiyu.com  
  48.   
  49.     Email Address []:caadmin@tjiyu.com  
  50.   
  51.     [root@node2 private]# ll  
  52.   
  53.     总用量 4  
  54.   
  55.     -rw-------. 1 root root 1675 10月 20 17:18 cakey.pem  
  56.   
  57. [root@node2 private]# cd ..  
  58.   
  59. [root@node2 CA]# touch serial  
  60.   
  61. [root@node2 CA]# echo 01 > serial  
  62.   
  63. [root@node2 CA]# touch index.txt  
  64.   
  65. [root@node2 CA]# ll  
  66.   
  67.     总用量 24  
  68.   
  69.     -rw-r--r--. 1 root root 1383 10月 20 17:25 cacert.pem  
  70.   
  71.     drwxr-xr-x. 2 root root 4096 9月 27 20:30 certs  
  72.   
  73.     drwxr-xr-x. 2 root root 4096 9月 27 20:30 crl  
  74.   
  75.     -rw-r--r--. 1 root root 0 10月 20 17:26 index.txt  
  76.   
  77.     drwxr-xr-x. 2 root root 4096 9月 27 20:30 newcerts  
  78.   
  79.     drwx------. 2 root root 4096 10月 20 17:18 private  
  80.   
  81.     -rw-r--r--. 1 root root 3 10月 20 17:26 serial  

2、生成证书申请

[plain] view plain copy
  1. [root@node2 CA]# mkdir /etc/nginx/ssl  
  2.   
  3. [root@node2 CA]# cd /etc/nginx/ssl/  
  4.   
  5. [root@node2 ssl]# (umask 077; openssl genrsa 1024 > nginx.key)  
  6.   
  7.     Generating RSA private key, 1024 bit long modulus  
  8.   
  9.     ....................................................++++++  
  10.   
  11.     ..............++++++  
  12.   
  13.     e is 65537 (0x10001)  
  14.   
  15.     [root@node2 ssl]# openssl req -new -key nginx.key -out nginx.csr  
  16.   
  17.     You are about to be asked to enter information that will be incorporated  
  18.   
  19.     into your certificate request.  
  20.   
  21.     What you are about to enter is what is called a Distinguished Name or a DN.  
  22.   
  23.     There are quite a few fields but you can leave some blank  
  24.   
  25.     For some fields there will be a default value,  
  26.   
  27.     If you enter '.', the field will be left blank.  
  28.   
  29.     -----  
  30.   
  31.     Country Name (2 letter code) [XX]:CN  
  32.   
  33.     State or Province Name (full name) []:HZ  
  34.   
  35.     Locality Name (eg, city) [Default City]:ZJ  
  36.   
  37.     Organization Name (eg, company) [Default Company Ltd]:TJIYU  
  38.   
  39.     Organizational Unit Name (eg, section) []:TEST  
  40.   
  41.     Common Name (eg, your name or your server's hostname) []:www.test.com  
  42.   
  43.     Email Address []:  
  44.   
  45.        
  46.   
  47.     Please enter the following 'extra' attributes  
  48.   
  49.     to be sent with your certificate request  
  50.   
  51.     A challenge password []:  
  52.   
  53.     An optional company name []:  

3、让CA签名并颁发证书

[plain] view plain copy
  1. [root@node2 ssl]# openssl ca -in nginx.csr -out nginx.crt -days 3650  
  2.   
  3.     Using configuration from /etc/pki/tls/openssl.cnf  
  4.   
  5.     Check that the request matches the signature  
  6.   
  7.     Signature ok  
  8.   
  9.     Certificate Details:  
  10.   
  11.     Serial Number: 1 (0x1)  
  12.   
  13.     Validity  
  14.   
  15.     Not Before: Oct 20 09:31:01 2016 GMT  
  16.   
  17.     Not After : Oct 18 09:31:01 2026 GMT  
  18.   
  19.     Subject:  
  20.   
  21.     countryName = CN  
  22.   
  23.     stateOrProvinceName = HZ  
  24.   
  25.     organizationName = TJIYU  
  26.   
  27.     organizationalUnitName = TEST  
  28.   
  29.     commonName = www.test.com  
  30.   
  31.     X509v3 extensions:  
  32.   
  33.     X509v3 Basic Constraints:  
  34.   
  35.     CA:FALSE  
  36.   
  37.     Netscape Comment:  
  38.   
  39.     OpenSSL Generated Certificate  
  40.   
  41.     X509v3 Subject Key Identifier:  
  42.   
  43.     AD:3D:C4:0D:11:A0:68:51:1B:CE:5E:45:B3:7C:A0:A8:2C:01:A8:27  
  44.   
  45.     X509v3 Authority Key Identifier:  
  46.   
  47.     keyid:5B:22:1A:8A:67:E6:C2:8A:CA:DA:F5:5C:97:86:76:5B:09:94:88:48  
  48.   
  49.        
  50.   
  51.     Certificate is to be certified until Oct 18 09:31:01 2026 GMT (3650 days)  
  52.   
  53.     Sign the certificate? [y/n]:y  
  54.   
  55.        
  56.   
  57.        
  58.   
  59.     1 out of 1 certificate requests certified, commit? [y/n]y  
  60.   
  61.     Write out database with 1 new entries  
  62.   
  63.     Data Base Updated  
  64.   
  65. [root@node2 ssl]# ll  
  66.   
  67.     总用量 12  
  68.   
  69.     -rw-r--r--. 1 root root 3736 10月 20 17:33 nginx.crt  
  70.   
  71.     -rw-r--r--. 1 root root 635 10月 20 17:30 nginx.csr  
  72.   
  73.     -rw-------. 1 root root 887 10月 20 17:27 nginx.key  

4、修改配置文件

      使用另外一个server配置SSL监听433端口,注意,配置如下:

[plain] view plain copy
  1. server {  
  2.   
  3.     listen 443 ssl; #打开SSL,监听433端口  
  4.   
  5.     server_name localhost;  
  6.   
  7.        
  8.   
  9.     ssl_certificate /etc/nginx/ssl/nginx.crt; #证书文件  
  10.   
  11.     ssl_certificate_key /etc/nginx/ssl/nginx.key; #证书key文件  
  12.   
  13.        
  14.   
  15.     ssl_session_cache shared:SSL:1m; #所有worker进程共享会话缓存  
  16.   
  17.     ssl_session_timeout 5m; #会话超时时间:5分钟  
  18.   
  19.        
  20.   
  21.     ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;     #支持SSL协议,从1.1.13和1.0.12版本开始支持TLSv1.1和TLSv1.2  
  22.   
  23.     ssl_ciphers HIGH:!aNULL:!MD5; #加密方法  
  24.   
  25.     ssl_prefer_server_ciphers on; #由服务器选择加密方法  
  26.   
  27.        
  28.   
  29.     location / {  
  30.   
  31.         root html;  
  32.   
  33.         index index.html index.htm;  
  34.   
  35.     }  
  36.   
  37. }  

5、测试

      重新加载配置后,查看网络状态,可以看到nginx监听了433端口;访问可以看到警告提示,因为我们的证书不是正规机构申请的,无法认证;继续访问可以看到正常页面 ,如下:

 

 

       到这里,我们成功对nginx进行了编译安装以及配置WEB服务相关内容,后面将进行nginx的反向代理、负载均衡、后端健康检测和缓存等相关功能配置……

相关内容

    暂无相关文章