Nginx系统学习篇(4)--linux环境配置

转自:http://freeloda.blog.51cto.com/2033581/1285722

一、Nginx 配置文件说明

1.查看一下配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
[root@web ~] # cat /etc/nginx/nginx.conf
#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;   
     #    server_name  localhost;
     #    ssl                  on;  
     #    ssl_certificate      cert.pem;   
     #    ssl_certificate_key  cert.key;
     #    ssl_session_timeout  5m;
     #    ssl_protocols  SSLv2 SSLv3 TLSv1;  
     #    ssl_ciphers  HIGH:!aNULL:!MD5;   
     #    ssl_prefer_server_ciphers   on;
     #    location / {  
     #        root   html;   
     #        index  index.html index.htm;   
     #    }   
     #}
}

2.nginx 配置文件结构

Nginx配置文件主要分为4部分:main(全局设置)、server(主机设置)、upstream(负载均衡服务器设置)和 location(URL匹配特定位置的设置)。main部分设置的指令将影响其他所有设置;server部分的指令主要用于指定主机和端口;upstream指令主要用于负载均衡,设置一系列的后端服务器;location部分用于匹配网页位置。这四者之间的关系如下:server继承main,location继承server,upstream既不会继承其他设置也不会被继承。如下图,

n3

在这4个部分当中,每个部分都包含若干指令,这些指令主要包含Nginx的主模块指令、事件模块指令、HTTP核心模块指令。同时每个部分还可以使用其他HTTP模块指令,例如Http SSL模块、Http Gzip Static模块和Http Addition模块等。

下面通过一个Nginx配置实例,详细介绍nginx.conf每个指令的含义。为了能更清楚地了解Nginx的结构和每个配置选项的含义,这里按照功能点将Nginx配置文件分为7个部分依次讲解。下面就围绕这7个部分进行介绍。

3.配置文件详解

(1).Nginx 的全局配置文件

1
2
3
4
5
6
7
8
9
10
11
#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;
worker_rlimit_nofile 65535; 
events {
     use epoll;
     worker_connections  1024;  
}

上面这段代码中每个配置选项的含义解释如下:

  • user是个主模块指令,指定Nginx Worker进程运行用户以及用户组,默认由nobody账号运行。

  • worker_processes是个主模块指令,指定了Nginx要开启的进程数。每个Nginx进程平均耗费10MB~12MB内存。根据经验,一般指定一个进程足够了,如果是多核CPU,建议指定和CPU的数量一样多的进程数即可。(注,如果负载以CPU密集型应用为主,如SSL或压缩应用,则worker数应与CPU数相同;如果负载以IO密集型为主,如响应大量内容给客户端,则worker数应该为CPU个数的1.5或2倍。)

  • error_log是个主模块指令,用来定义全局错误日志文件。日志输出级别有debug、info、notice、warn、error、crit可供选择,其中,debug输出日志最为最详细,而crit输出日志最少。

  • pid是个主模块指令,用来指定进程id的存储文件位置。

  • worker_rlimit_nofile 用于绑定worker进程和CPU, Linux内核2.4以上可用。

  • events指令用来设定Nginx的工作模式及连接数上限。

  • use是个事件模块指令,用来指定Nginx的工作模式。Nginx支持的工作模式有select、poll、kqueue、epoll、rtsig和/dev/poll。其中select和poll都是标准的工作模式,kqueue和epoll是高效的工作模式,不同的是epoll用在Linux平台上,而kqueue用在BSD系统中。对于Linux系统,epoll工作模式是首选。

  • worker_connections也是个事件模块指令,用于定义Nginx每个进程的最大连接数,默认是1024。最大客户端连接数由worker_processes和worker_connections决定,即max_client=worker_processes*worker_connections,在作为反向代理时变为:max_clients = worker_processes * worker_connections/4。(注,进程的最大连接数受Linux系统进程的最大打开文件数限制,在执行操作系统命令“ulimit -n 65536”后worker_connections的设置才能生效。)

(2).HTTP服务器配置

注,接下来开始对HTTP服务器进行配置。下面这段内容是Nginx对HTTP服务器相关属性的配置,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
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;

下面详细介绍这段代码中每个配置选项的含义。

  • include是个主模块指令,实现对配置文件所包含的文件的设定,可以减少主配置文件的复杂度。类似于Apache中的include方法。

  • default_type属于HTTP核心模块指令,这里设定默认类型为二进制流,也就是当文件类型未定义时使用这种方式,例如在没有配置PHP环境时,Nginx是不予解析的,此时,用浏览器访问PHP文件就会出现下载窗口。

  • log_format是Nginx的HttpLog模块指令,用于指定Nginx日志的输出格式。main为此日志输出格式的名称,可以在下面的access_log指令中引用。

  • client_max_body_size用来设置允许客户端请求的最大的单个文件字节数。

  • client_header_buffer_size用于指定来自客户端请求头的headerbuffer大小。对于大多数请求,1KB的缓冲区大小已经足够,如果自定义了消息头或有更大的cookie,可以增加缓冲区大小。这里设置为32KB。

  • large_client_header_buffers用来指定客户端请求中较大的消息头的缓存最大数量和大小, “4”为个数,“128K”为大小,最大缓存为4个128KB。

  • sendfile参数用于开启高效文件传输模式。将tcp_nopush和tcp_nodely两个指令设置为on,用于防止网络阻塞。

  • keepalive_timeout用于设置客户端连接保持活动的超时时间。在超过这个时间之后,服务器会关闭该连接。

  • client_header_timeout用于设置客户端请求头读取超时时间。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误。

  • client_body_timeout用于设置客户端请求主体读取超时时间,默认值为60。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误。

  • send_timeout用于指定响应客户端的超时时间。这个超时仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,Nginx将会关闭连接。

  • gzip用于设置开启或者关闭gzip模块,“gzip on”表示开启gzip压缩,实时压缩输出数据流。

(3).HttpGzip模块配置

下面配置Nginx的HttpGzip模块。这个模块支持在线实时压缩输出数据流。要查看是否安装了此模块,需要使用下面的命令:

1
2
3
4
5
[root@web nginx-1.4.2] # nginx -V  
nginx version: nginx /1 .4.2   
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC)   
TLS SNI support enabled   
configure arguments: --prefix= /usr  --sbin-path= /usr/sbin/nginx  --conf-path= /etc/nginx/nginx .conf --error-log-path= /var/log/nginx/error .log --http-log-path= /var/log/nginx/access .log --pid-path= /var/run/nginx/nginx .pid --lock-path= /var/lock/nginx .lock --user=nginx --group=nginx --with-http_ssl_module --with-http_flv_module --with-http_stub_status_module --with-http_gzip_static_module --http-client-body-temp-path= /var/tmp/nginx/client/  --http-proxy-temp-path= /var/tmp/nginx/proxy/  --http-fastcgi-temp-path= /var/tmp/nginx/fcgi/  --http-uwsgi-temp-path= /var/tmp/nginx/uwsgi  --http-scgi-temp-path= /var/tmp/nginx/scgi  --with-pcre

通过nginx -V 命令可以查看安装Nginx时的编译选项。由输出可知,我们已经安装了HttpGzip模块。下面是HttpGzip模块在Nginx配置中的相关属性设置:

1
2
3
4
5
6
7
#gzip  on;
#gzip_min_length  1k;
#gzip_buffers     4  16k;
#gzip_http_version  1.1;
#gzip_comp_level  2;
#gzip_types  text/plain application/x-javascript text/css application/xml;
#gzip_vary  on;
  • gzip用于设置开启或者关闭gzip模块,“gzip on”表示开启gzip压缩,实时压缩输出数据流。

  • gzip_min_length用于设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取。默认值是0,不管页面多大都进行压缩。建议设置成大于1K的字节数,小于1K可能会越压越大。

  • gzip_buffers表示申请4个单位为16K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。

  • gzip_buffers表示申请4个单位为16K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。

  • gzip_comp_level用来指定gzip压缩比,1 压缩比最小,处理速度最快;9 压缩比最大,传输速度快,但处理最慢,也比较消耗CPU资源。

  • gzip_types用来指定压缩的类型,无论是否指定,“text/html”类型总是会被压缩的。

  • gzip_vary选项可以让前端的缓存服务器缓存经过gzip压缩的页面,例如,用Squid缓存经过Nginx压缩的数据。

(4).负载均衡配置

下面设定负载均衡的服务器列表。

1
2
3
4
5
6
7
upstream  test .net{
ip_hash;
server 192.168.10.13:80;
server 192.168.10.14:80  down;
server 192.168.10.15:8009  max_fails=3  fail_timeout=20s;
server 192.168.10.16:8080;
}
  • upstream是Nginx的HTTP Upstream模块,这个模块通过一个简单的调度算法来实现客户端IP到后端服务器的负载均衡。在上面的设定中,通过upstream指令指定了一个负载均衡器的名称test.net。这个名称可以任意指定,在后面需要用到的地方直接调用即可。

  • Nginx的负载均衡模块目前支持4种调度算法,下面进行分别介绍,其中后两项属于第三方调度算法。      

  • 轮询(默认)。每个请求按时间顺序逐一分配到不同的后端服务器,如果后端某台服务器宕机,故障系统被自动剔除,使用户访问不受影响。

  • Weight。指定轮询权值,Weight值越大,分配到的访问机率越高,主要用于后端每个服务器性能不均的情况下。

  • ip_hash。每个请求按访问IP的hash结果分配,这样来自同一个IP的访客固定访问一个后端服务器,有效解决了动态网页存在的session共享问题。

  • fair。这是比上面两个更加智能的负载均衡算法。此种算法可以依据页面大小和加载时间长短智能地进行负载均衡,也就是根据后端服务器的响应时间来分配请求,响应时间短的优先分配。Nginx本身是不支持fair的,如果需要使用这种调度算法,必须下载Nginx的upstream_fair模块。

  • url_hash。此方法按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,可以进一步提高后端缓存服务器的效率。Nginx本身是不支持url_hash的,如果需要使用这种调度算法,必须安装Nginx 的hash软件包。

  • 在HTTP Upstream模块中,可以通过server指令指定后端服务器的IP地址和端口,同时还可以设定每个后端服务器在负载均衡调度中的状态。常用的状态有:      

  • down,表示当前的server暂时不参与负载均衡。

  • backup,预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候,才会请求backup机器,因此这台机器的压力最轻。

  • max_fails,允许请求失败的次数,默认为1。当超过最大次数时,返回proxy_next_upstream 模块定义的错误。

  • fail_timeout,在经历了max_fails次失败后,暂停服务的时间。max_fails可以和fail_timeout一起使用。

注意,当负载调度算法为ip_hash时,后端服务器在负载均衡调度中的状态不能是weight和backup。

(5).server虚拟主机配置

下面介绍对虚拟主机的配置。建议将对虚拟主机进行配置的内容写进另外一个文件,然后通过include指令包含进来,这样更便于维护和管理。

1
2
3
4
5
6
7
server{
listen         80;
server_name    192.168.12.188  www. test .net;
index index.html index.htm index.php;
root   /web/www/www . test .net
charset gb2312;
access_log  logs /www . test .net.access.log  main;
  • server标志定义虚拟主机开始;

  • listen用于指定虚拟主机的服务器端口;

  • server_name用来指定IP地址或者域名,多个域名之间用空格分开;

  • index用于设定访问的默认首页地址;

  • root指令用于指定虚拟主机的网页根目录,这个目录可以是相对路径,也可以是绝对路径;

  • charset用于设置网页的默认编码格式。

  • access_log用来指定此虚拟主机的访问日志存放路径。最后的main用于指定访问日志的输出格式。

(6).URL匹配配置

URL地址匹配是Nginx配置中最灵活的部分。 location支持正则表达式匹配,也支持条件判断匹配,用户可以通过location指令实现Nginx对动、静态网页的过滤处理。

格式:location [ = | ~ | ~* | ^~ ] uri { ... }

  • location URI {}:对当前路径及子路径下的所有对象都生效;

  • location = URI {}:精确匹配指定的路径,不包括子路径,因此,只对当前资源生效;

  • location ~ URI {},location ~* URI {}:模式匹配URI,此处的URI可使用正则表达式,~区分字符大小写,~*不区分字符大小写;

  • location ^~ URI {}:不使用正则表达式

案例1:

1
2
3
4
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  {
                     root     /web/www/www . test .net;
                     expires 30d;
        }

说明:上面这段设置是通过location指令来对网页URL进行分析处理,所有扩展名为.gif、.jpg、.jpeg、.png、.bmp、.swf的静态文件都交给Nginx处理,而expires用来指定静态文件的过期时间,这里是30天。

案例2:

1
2
3
4
location ~ ^/(upload|html)/  {
                 root     /web/www/www . test .net;
                 expires 30d;
}

说明:上面这段设置是将upload和html下的所有文件都交给Nginx来处理,当然,upload和html目录包含/web/www/www.test.net目录中。

案例3:

1
2
3
4
location ~ .*.jsp$ {
             index index.jsp;
             proxy_pass http: //localhost :8080;
           }

说明:在最后这段设置中,location是对此虚拟主机下动态网页的过滤处理,也就是将所有以.jsp为后缀的文件都交给本机的8080端口处理。

location [ = | ~ | ~* | ^~ ] 优先级

  • location = URI {}:精确匹配指定的路径,不包括子路径,因此,只对当前资源生效;(优先级最高)

  • location ^~ URI {}:不使用正则表达式;(优先级次之)

  • location ~ URI {},location ~* URI {}:模式匹配URI,此处的URI可使用正则表达式,~区分字符大小写,~*不区分字符大小写;(优先级次之)

  • location URI {}:对当前路径及子路径下的所有对象都生效;(优先级最低)

案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
location = / {  
     [ configuration A ]
}
location / {  
     [ configuration B ]
}
location /documents/ {
     [ configuration C ]
}
location ^~ /images/
{  
     [ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {  
     [ configuration E ]
}

说明:The “/” request will match configuration A, the “/index.html” request will match configuration B, the “/documents/document.html” request will match configuration C, the “/images/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E.

(7).StubStatus模块配置

StubStatus模块能够获取Nginx自上次启动以来的工作状态,此模块非核心模块,需要在Nginx编译安装时手工指定才能使用。以下指令指定启用获取Nginx工作状态的功能。

1
2
3
4
5
6
location  /NginxStatus  {
     stub_status     on;
     access_log             logs /NginxStatus .log;
     auth_basic              "NginxStatus" ;
     auth_basic_user_file    .. /htpasswd ;
        }

  • stub_status为“on”表示启用StubStatus的工作状态统计功能;

  • access_log 用来指定StubStatus模块的访问日志文件;

  • auth_basic是Nginx的一种认证机制;

  • auth_basic_user_file用来指定认证的密码文件。

由于Nginx的auth_basic认证采用的是与Apache兼容的密码文件,因此需要用Apache的htpasswd命令来生成密码文件。例如要添加一个webadmin用户,可以使用下面的方式生成密码文件:

1
/usr/local/apache/bin/htpasswd  -c   /opt/nginx/conf/htpasswd  webadmin

要查看Nginx的运行状态,可以输入http://ip/ NginxStatus,然后输入刚刚创建的用户名和密码就可以看到如下信息:

1
2
3
4
Active connections: 1
server accepts handled requests
393411 393411 393799
Reading: 0 Writing: 1 Waiting: 0
  • Active connections表示当前活跃的连接数。

  • 第三行的3个数字表示 Nginx当前总共处理了393411个连接, 成功创建了393 411次握手,总共处理了393 799个请求。

  • 最后一行的Reading表示Nginx读取到客户端Header信息数; Writing表示Nginx返回给客户端的Header信息数;Waiting表示Nginx已经处理完、正在等候下一次请求指令时的驻留连接数。

补充说明:

1
2
3
4
5
error_page  404               /404 .html;
error_page   500 502 503 504   /50x .html;
location =  /50x .html {
            root   html;
        }

在最后这段设置中,设置了虚拟主机的错误信息返回页面,通过error_page指令可以定制各种错误信息的返回页面。在默认情况下,Nginx会在主目录的html目录中查找指定的返回页面。特别需要注意的是,这些错误信息的返回页面大小一定要超过512KB,否则会被IE浏览器替换为IE默认的错误页面。好了,到这里nginx的配置文件讲解全部完成。下面我们来说一说nginx命令参数。

二、Nginx 命令参数

不像许多其他软件系统,Nginx 仅有数个命令行参数,完全通过配置文件来配置(想象一下)。

  • [#options 选项]

  • [#example 示例]

  • [#lncus 使用信号加载新的配置]

  • [#utnbotf 平滑升级到新的二进制代码]

选项

  • -c </path/to/config> 为 Nginx 指定一个配置文件,来代替缺省的。

  • -t 不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。

  • -v 显示 nginx 的版本。

  • -V 显示 nginx 的版本,编译器版本和配置参数。

更多

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@web ~] # nginx -h 
nginx version: nginx /1 .4.2 
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options: 
   -?,-h         : this help 
   - v             : show version and  exit 
   -V            : show version and configure options  then  exit 
   -t            :  test  configuration and  exit 
   -q            : suppress non-error messages during configuration testing 
   -s signal     : send signal to a master process: stop, quit, reopen, reload 
   -p prefix     :  set  prefix path (default:  /usr/
   -c filename   :  set  configuration  file  (default:  /etc/nginx/nginx .conf) 
   -g directives :  set  global directives out of configuration  file

三、配置Nginx提供Web服务

1.提供测页面

1
2
3
4
5
6
7
8
[root@web nginx] # mkdir -pv /data/www 
mkdir : 已创建目录  "/data/www" 
[root@web nginx] # cd /data/www 
[root@web www] # ll 
总用量 0
[root@web www] # cat index.html
<h1>www.nginx.org< /h1 >
[root@web www] # chown -R nginx.nginx /data/www/*

2.备份配置文件

1
2
3
4
5
6
[root@web ~] # cd /etc/nginx/ 
[root@web nginx] # cp nginx.conf nginx.conf.bak 
[root@web nginx] # ls 
fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf.bak      scgi_params.default   win-utf 
fastcgi.conf.default  koi-utf                 mime.types.default  nginx.conf.default  uwsgi_params 
fastcgi_params        koi-win                 nginx.conf          scgi_params         uwsgi_params.default

3.修改配置文件

1
2
3
4
5
6
7
8
9
10
[root@web www] # vim /etc/nginx/nginx.conf
server { 
       listen       80; 
       server_name  localhost;
       #charset koi8-r;
       #access_log  logs/host.access.log  main;
       location / { 
           root    /data/www
           index  index.html index.htm; 
       }

4.重新加载nginx配置

1
2
3
4
[root@web run] # service nginx reload
nginx: the configuration  file  /etc/nginx/nginx .conf syntax is ok
nginx: configuration  file  /etc/nginx/nginx .conf  test  is successful
重新载入 nginx:                                           [确定]

5.测试一下

n4

好了,一个基本的web服务器已配置完成,简单吧。

四、配置Nginx的虚拟主机

1.修改配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@web www] # vim /etc/nginx/nginx.conf
server { 
         listen       80; 
         server_name  www.nginx.com; 
         location / { 
             root    /data/www
             index  index.html index.htm; 
        
     }
     server { 
         listen       80; 
         server_name  www. test .com; 
         location / { 
             root    /data/test
             index  index.html index.htm; 
        
     }

2.提供测试页面

1
2
3
4
[root@web data] # mkdir test 
[root@web data] # cd test/ 
[root@web  test ] # cat index.html 
<h1>www. test .com< /h1 >

3.重新加载nginx配置

1
2
3
4
[root@web run] # service nginx reload 
nginx: the configuration  file  /etc/nginx/nginx .conf syntax is ok 
nginx: configuration  file  /etc/nginx/nginx .conf  test  is successful 
重新载入 nginx:                                           [确定]

4.修改测试机的hosts文件

1
2
3
4
Windows 7下路径:C:\Windows\System32\drivers\etc\hosts
增加两行:
192.168.18.201    www.nginx.com 
192.168.18.201    www. test .com

5.测试一下

n5

n6

好了,到这里基于域名的虚拟主机配置完成。

五、配置Nginx的访问控制

基于用户的访问控制,

1.提供测试文件

1
2
3
4
5
6
7
8
9
[root@web run] # cd /data/www/ 
[root@web www] # ll 
总用量 4 
-rw-r--r-- 1 nginx nginx 23 8月  29 20:04 index.html 
[root@web www] # mkdir bbs 
[root@web www] # cd bbs/ 
[root@web bbs] # vim index.html 
[root@web bbs] # cat index.html 
<h1>Auth Page< /h1 >

2.修改配置文件

1
2
3
4
5
6
location  /data 
            root  /www/bbs
            index index.html 
            auth_basic              "Auth Page" ;
            auth_basic_user_file   /etc/nginx/ .user; 
        }

3.安装httpd

1
[root@web bbs] # yum install -y httpd

4.生成认证文件

1
2
3
4
5
6
7
8
9
[root@web bbs] # htpasswd -c -m /etc/nginx/.user nginx 
New password: 
Re- type  new password: 
Adding password  for  user nginx 
[root@web bbs] # ls -a /etc/nginx/ 
.                     fastcgi_params          mime.types          nginx.conf.default   .user 
..                    fastcgi_params.default  mime.types.default  .nginx.conf.swp      uwsgi_params 
fastcgi.conf          koi-utf                 nginx.conf          scgi_params          uwsgi_params.default 
fastcgi.conf.default  koi-win                 nginx.conf.bak      scgi_params.default  win-utf

5.重新加载一下nginx配置文件

1
2
3
4
[root@web bbs] # service nginx reload 
nginx: the configuration  file  /etc/nginx/nginx .conf syntax is ok 
nginx: configuration  file  /etc/nginx/nginx .conf  test  is successful 
重新载入 nginx:                                           [确定]

6.测试一下

(1).输入用户名nginx,密码123456

n7

(2).显示页面

n8

基于IP的访问控制,

1.控制指令

  • allow 定义允许访问的规则

  • deny 定义拒绝访问的规则

  • allow all或deny all 定义默认规则

2.案例

1
2
3
4
5
6
7
8
9
10
[root@web  test ] # vim /etc/nginx/nginx.conf
location / { 
          root    /data/www
          index  index.html index.htm; 
          #auth_basic "Auth Page";           
          #auth_basic_user_file /etc/nginx/.user; 
          deny 192.168.18.138; 
          allow 192.168.18.0 /24 ;
          deny  all; 
      }

n9

注,大家可以看到不允许访问。allow与deny指令使用很简单,唯一与httpd不同的是nginx没有定义默认规则,所以默认规则得自己定义。我这里定义是dell all;默认拒绝所有。

六、配置Nginx提供状态页面

1.修改配置文件

1
2
3
4
5
6
7
[root@web  test ] # vim /etc/nginx/nginx.conf
location  /status 
      root /; 
      stub_status on; 
      auth_basic  "NginxStatus" ;              
      auth_basic_user_file  /etc/nginx/ .user; 
      }

2.重新加载一下配置文件

3.测试

n10

n11

九、配置Nginx的错误页面

1.提供404错误页面

1
2
3
4
5
6
7
8
9
10
11
[root@web www] # ll 
总用量 8 
drwxr-xr-x 2 root  root  4096 8月  29 20:36 bbs 
-rw-r--r-- 1 nginx nginx   23 8月  29 20:04 index.html 
[root@web www] # vim 404.html 
[root@web www] # cat 404.html 
<h1>404 error< /h1 >
<h1>404 error< /h1 >
<h1>404 error< /h1 >
<h1>404 error< /h1 >
……

2.修改配置文件

1
2
3
4
[root@web  test ] # vim /etc/nginx/nginx.conf
server {
error_page  404                  /404 .html;
}

3.重新加载一下nginx配置文件

1
2
3
4
[root@web www] # service nginx reload 
nginx: the configuration  file  /etc/nginx/nginx .conf syntax is ok 
nginx: configuration  file  /etc/nginx/nginx .conf  test  is successful 
重新载入 nginx:                                           [确定]

4.我们访问一下不存在的页面

n12

七、配置Nginx打开目录浏览功能

1.指令说明

Nginx默认是不允许列出整个目录的。如需此功能,打开nginx.conf文件,在location server 或 http段中加入autoindex on;另外两个参数最好也加上去,

  • autoindex_exact_size off;默认为on,显示出文件的确切大小,单位是bytes。改为off后,显示出文件的大概大小,单位是kB或者MB或者GB。

  • autoindex_localtime on;默认为off,显示的文件时间为GMT时间。改为on后,显示的文件时间为文件的服务器时间。

2.修改配置文件

1
2
3
4
5
6
7
8
9
10
11
server { 
     listen       80; 
     server_name  www.nginx.com; 
     location / { 
     autoindex on; 
     autoindex_exact_size on; 
     autoindex_localtime on; 
     root    /data/www
     index  123.html; 
    
}

3.重新加载配置文件

1
2
3
4
[root@web www] # service nginx reload 
nginx: the configuration  file  /etc/nginx/nginx .conf syntax is ok 
nginx: configuration  file  /etc/nginx/nginx .conf  test  is successful 
重新载入 nginx:                                           [确定]

4.测试一下

n13

八、配置Nginx基于ssl提供https服务

1.创建CA自签证书

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[root@web ~] # cd /etc/pki/CA/ 
[root@web CA] # ls 
certs  crl  newcerts  private 
[root@web CA] # cd private/ 
[root@web private] # ls 
[root@web private] # (umask 077; openssl genrsa 2048 > cakey.pem) #生成私钥 
Generating RSA private key, 2048 bit long modulus 
...............................+++ 
.............+++ 
e is 65537 (0x10001) 
[root@web CA] # openssl req -new -x509 -key ./private/cakey.pem -out cacert.pem #生成自签证书 
You are about to be asked to enter information that will be incorporated 
into your certificate request. 
What you are about to enter is what is called a Distinguished Name or a DN. 
There are quite a few fields but you can leave some blank 
For some fields there will be a default value, 
If you enter  '.' , the field will be left blank. 
----- 
Country Name (2 letter code) [XX]:CN 
State or Province Name (full name) []:SH 
Locality Name (eg, city) [Default City]:XH  
Organization Name (eg, company) [Default Company Ltd]:JJHH    
Organizational Unit Name (eg, section) []:Tech 
Common Name (eg, your name or your server's  hostname ) []:ca. test .com 
Email Address []:caadmin@ test .com 
[root@web private] # ll 
总用量 8 
-rw------- 1 root root 1679 8月  29 23:31 cakey.pem 
[root@web CA] # touch serial 
[root@web CA] # echo 01 > serial 
[root@web CA] # touch index.txt
[root@web CA] # ll 
总用量 24 
-rw-r--r--  1 root root 1375 8月  29 23:34 cacert.pem 
drwxr-xr-x. 2 root root 4096 3月   5 06:22 certs 
drwxr-xr-x. 2 root root 4096 3月   5 06:22 crl 
-rw-r--r--  1 root root    0 8月  29 23:35 index.txt 
drwxr-xr-x. 2 root root 4096 3月   5 06:22 newcerts 
drwx------. 2 root root 4096 8月  29 23:49 private 
-rw-r--r--  1 root root    3 8月  29 23:35 serial

2.生成证书申请

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@web ~] # mkdir /etc/nginx/ssl 
[root@web CA] # cd /etc/nginx/ssl/
[root@web ssl] # (umask 077; openssl genrsa 1024 > nginx.key) #生成私钥 
Generating RSA private key, 1024 bit long modulus 
.........................................++++++ 
..................................++++++ 
e is 65537 (0x10001)
[root@web ssl] # openssl req -new -key nginx.key -out nginx.csr 
You are about to be asked to enter information that will be incorporated 
into your certificate request. 
What you are about to enter is what is called a Distinguished Name or a DN. 
There are quite a few fields but you can leave some blank 
For some fields there will be a default value, 
If you enter  '.' , the field will be left blank. 
----- 
Country Name (2 letter code) [XX]:CN 
State or Province Name (full name) []:SH 
Locality Name (eg, city) [Default City]:XH 
Organization Name (eg, company) [Default Company Ltd]:JJHH 
Organizational Unit Name (eg, section) []:Tech 
Common Name (eg, your name or your server's  hostname ) []:www. test .com 
Email Address []:
Please enter the following  'extra'  attributes 
to be sent with your certificate request 
A challenge password []: 
An optional company name []:

3. 让CA签名并颁发证书

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[root@web ssl] # openssl ca -in nginx.csr -out nginx.crt -days 3650 
Using configuration from  /etc/pki/tls/openssl .cnf 
Check that the request matches the signature 
Signature ok 
Certificate Details: 
         Serial Number: 1 (0x1) 
         Validity 
             Not Before: Aug 29 15:51:53 2013 GMT 
             Not After : Aug 27 15:51:53 2023 GMT 
         Subject: 
             countryName               = CN 
             stateOrProvinceName       = SH 
             organizationName          = JJHH 
             organizationalUnitName    = Tech 
             commonName                = www. test .com 
         X509v3 extensions: 
             X509v3 Basic Constraints: 
                 CA:FALSE 
             Netscape Comment: 
                 OpenSSL Generated Certificate 
             X509v3 Subject Key Identifier: 
                 60:87:97:14:D5:A2:23:B9:C5:13:97:5D:0D:B9:D7:C3:C2:66:F0:4B 
             X509v3 Authority Key Identifier: 
                 keyid:9E:3E:5B:84:06:BE:68:01:C9:16:7C:08:5F:C5:54:0D:7B:FC:FA:87
Certificate is to be certified  until  Aug 27 15:51:53 2023 GMT (3650 days) 
Sign the certificate? [y /n ]:y
1 out of 1 certificate requests certified, commit? [y /n ]y 
Write out database with 1 new entries 
Data Base Updated

4.修改配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server { 
       listen       443; 
       server_name  localhost;
       ssl                  on; 
       ssl_certificate       /etc/nginx/ssl/nginx .crt; 
       ssl_certificate_key   /etc/nginx/ssl/nginx .key;
       ssl_session_timeout  5m;
       ssl_protocols  SSLv2 SSLv3 TLSv1; 
       ssl_ciphers  HIGH:!aNULL:!MD5; 
       ssl_prefer_server_ciphers   on;
       location / { 
           root   html; 
           index  index.html index.htm; 
      
   }

5.重新启动一下nginx服务器

1
2
3
4
5
[root@web ssl] # service nginx restart 
nginx: the configuration  file  /etc/nginx/nginx .conf syntax is ok 
nginx: configuration  file  /etc/nginx/nginx .conf  test  is successful 
停止 nginx:                                               [确定] 
正在启动 nginx:                                           [确定]

6.查看一下端口   

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@web ssl] # netstat -ntlp 
Active Internet connections (only servers) 
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID /Program  name 
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      10661 /nginx       
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1033 /sshd         
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1110 /master       
tcp        0      0 127.0.0.1:6010              0.0.0.0:*                   LISTEN      9599 /sshd         
tcp        0      0 0.0.0.0:443                 0.0.0.0:*                   LISTEN      10661 /nginx       
tcp        0      0 127.0.0.1:6012              0.0.0.0:*                   LISTEN      9470 /sshd         
tcp        0      0 :::22                       :::*                        LISTEN      1033 /sshd         
tcp        0      0 ::1:25                      :::*                        LISTEN      1110 /master       
tcp        0      0 ::1:6010                    :::*                        LISTEN      9599 /sshd         
tcp        0      0 ::1:6012                    :::*                        LISTEN      9470 /sshd

7.测试一下

n14

n15

好了,nginx作为Web服务器的基本配置全部演示完成


猜你喜欢

转载自blog.csdn.net/DADADIE/article/details/52093645