Home > Backend Development > PHP Tutorial > Detailed explanation of Nginx installation and configuration file nginxconf

Detailed explanation of Nginx installation and configuration file nginxconf

WBOY
Release: 2016-08-08 09:21:17
Original
1205 people have browsed it
1. Install Nginx

Before installing Nginx, make sure that the system has installed the gcc, openssl-devel, pcre-devel and zlib-devel software libraries.
The following is the Nginx installation process:

wget http://nginx.org/download/nginx-1.0.14.tar.gz
tar zxvf nginx-1.0.14.tar.gz
./configure --with-http_stub_status_module --prefix=/opt/nginx
cd nginx-1.0.14
make
make install
Copy after login

Among them, –with-http_stub_status_module can be used to enable the NginxStatus function of Nginx to monitor the running status of Nginx.
If you want to know more about the modules, you can check it through the ./configure –help option.

2. Nginx configuration file structure
Nginx’s configuration file nginx.conf is located in the conf directory of its installation directory.
nginx.conf consists of multiple blocks. The outermost block is main. Main contains Events and HTTP. HTTP contains upstream and multiple servers. Server contains multiple locations:

main (global settings), server ( Host settings), upstream (load balancing server settings) and location (URL matches a specific location settings). The instructions set by the

  • main block will affect all other settings; the instructions of the
  • server block are mainly used to specify the host and port; the
  • upstream instructions are mainly used for load balancing and setting up a series of backend servers;
  • location block Used to match web page locations.

The relationship between these four: server inherits main, location inherits server, and upstream will neither inherit other settings nor be inherited.
Among these four parts, each part contains a number of instructions. These instructions mainly include Nginx's main module instructions, event module instructions, and HTTP core module instructions. At the same time, each part can also use other HTTP module instructions, such as Http SSL module, HttpGzip Static module and Http Addition module, etc.

2.1 The global configuration of Nginx

The code is as follows:

1
2
3
4
5
6
7
8
9
10
Copy after login
user  nobody nobody;
worker_processes  2;
error_log  logs/error.log  notice;
pid        logs/nginx.pid;
worker_rlimit_nofile 65535;
 
events{
     use epoll;
     worker_connections      65536;
}
Copy after login

The meaning of each configuration option is explained as follows:

  • user is a master Module directive, specify Nginx The Worker process runs under the user and user group, and is run by the nobody account by default.
  • worker_processes is a main module instruction that specifies the number of processes to be opened by Nginx. Each Nginx process consumes an average of 10M~12M of memory. It is recommended to specify the same number as the number of CPUs.
  • error_log is a main module directive used to define a global error log file. Log output levels include debug, info, notice, warn, error, and crit to choose from. Among them, debug output log is the most detailed, while crit output log is the least.
  • pid is a main module instruction, used to specify the storage file location of the process pid.
  • worker_rlimit_nofile is used to bind the worker process and CPU. It is available in Linux kernel 2.4 and above.

events event command is to set the working mode and upper limit of the number of connections of Nginx:
use is an event module command used to specify the working mode of Nginx. The working modes supported by Nginx are select, poll, kqueue, epoll, rtsig and /dev/poll. Among them, select and poll are standard working modes, and kqueue and epoll are efficient working modes. The difference is that epoll is used on the Linux platform, while kqueue is used on the BSD system. For Linux systems, the epoll working mode is the first choice.
worker_connections is also an event module directive, used to define the maximum number of connections for each Nginx process. The default is 1024. The maximum number of client connections is determined by worker_processes and worker_connections, that is, Max_client=worker_processes*worker_connections.
When acting as a reverse proxy, max_clients becomes: max_clients = worker_processes * worker_connections/4.
The maximum number of connections of a process is limited by the maximum number of open files of the Linux system process. The setting of worker_connections can only take effect after executing the operating system command "ulimit -n 65536"

2.2 HTTP server configuration
Nginx's HTTP server related attributes The configuration code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Copy after login
http{
http{
	include      conf/mime.types;
	default_type  application/octet-stream;
	log_format main '$remote_addr - $remote_user [$time_local] '
	'"$request" $status $bytes_sent '
	'"$http_referer" "$http_user_agent" '
	'"$gzip_ratio"';
	log_format download '$remote_addr - $remote_user [$time_local] '
	'"$request" $status $bytes_sent '
	'"$http_referer" "$http_user_agent" '
	'"$http_range" "$sent_http_content_range"';
	client_max_body_size  20m;
	client_header_buffer_size    32K;
	large_client_header_buffers  4 32k;
	Sendfile  on;
	tcp_nopush     on;
	tcp_nodelay    on;
	keepalive_timeout 60;
	client_header_timeout  10;
	client_body_timeout    10;
	send_timeout          10;
Copy after login

The following is a detailed introduction to the meaning of each configuration option in this code.
include is a main module instruction that enables the setting of files included in the configuration file, which can reduce the complexity of the main configuration file. Similar to the include method in Apache.
default_type belongs to the HTTP core module directive. Here, the default type is set to binary stream, which is used when the file type is not defined. For example, when the PHP environment is not configured, Nginx will not parse it. At this time, use Browse When the PHP file is accessed by the server, a download window will appear.

The following code implements setting the log format:

1
2
3
4
5
6
7
8
Copy after login
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
log_format download '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_range" "$sent_http_content_range"';
Copy after login

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

  • client_max_body_size用来设置允许客户端请求的最大的单个文件字节数;
  • client_header_buffer_size用于指定来自客户端请求头的headerbuffer大小。对于大多数请求,1K的缓冲区大小已经足够,如果自定义了消息头或有更大的Cookie,可以增加缓冲区大小。这里设置为32K;
  • large_client_header_buffers用来指定客户端请求中较大的消息头的缓存最大数量和大小, “4”为个数,“128K”为大小,最大缓存量为4个128K;
  • sendfile参数用于开启高效文件传输模式。将tcp_nopush和tcp_nodelay两个指令设置为on用于防止网络阻塞;
  • keepalive_timeout设置客户端连接保持活动的超时时间。在超过这个时间之后,服务器会关闭该连接;
  • client_header_timeout设置客户端请求头读取超时时间。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误;
  • client_body_timeout设置客户端请求主体读取超时时间。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误,默认值是60;
  • send_timeout指定响应客户端的超时时间。这个超时仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,Nginx将会关闭连接。

2.3 HttpGzip模块配置
下面配置Nginx的HttpGzip模块。这个模块支持在线实时压缩输出数据流。
看是否安装了HttpGzip模块:

[root@vps ~]# /opt/nginx/sbin/nginx  -V
nginx version: nginx/1.0.14
built by gcc 4.4.6 20110731 (Red Hat 4.4.6-3) (GCC)
configure arguments: --with-http_stub_status_module --with-http_gzip_static_module --prefix=/opt/nginx
Copy after login

通过/opt/nginx/sbin/nginx -V命令可以查看安装Nginx时的编译选项,由输出可知,我们已经安装了HttpGzip模块。

下面是HttpGzip模块在Nginx配置中的相关属性设置:

1
2
3
4
5
6
7
Copy after login
Copy after login
Copy after login
Copy after login
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;
Copy after login
  • gzip用于设置开启或者关闭gzip模块,“gzip on”表示开启GZIP压缩,实时压缩输出数据流;
  • gzip_min_length设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取。默认值是0,不管页面多大都进行压缩。建议设置成大于1K的字节数,小于1K可能会越压越大;
  • gzip_buffers表示申请4个单位为16K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果;
  • gzip_http_version用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持GZIP解压,使用默认即可;
  • gzip_comp_level用来指定GZIP压缩比,1 压缩比最小,处理速度最快;9 压缩比最大,传输速度快,但处理最慢,也比较消耗cpu资源;
  • gzip_types用来指定压缩的类型,无论是否指定,“text/html”类型总是会被压缩的;
  • gzip_vary选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用Squid缓存经过Nginx压缩的数据。

2.4 负载均衡配置
下面设定负载均衡的服务器列表:

1
2
3
4
5
6
7
Copy after login
Copy after login
Copy after login
Copy after login
upstream cszhi.com{
	ip_hash;
	server 192.168.8.11:80;
	server 192.168.8.12:80  down;
	server 192.168.8.13:8009  max_fails=3  fail_timeout=20s;
	server 192.168.8.146:8080;
}
Copy after login

upstream是Nginx的HTTP Upstream模块,这个模块通过一个简单的调度算法来实现客户端IP到后端服务器的负载均衡。
在上面的设定中,通过upstream指令指定了一个负载均衡器的名称cszhi.com。这个名称可以任意指定,在后面需要的地方直接调用即可。

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。

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

1
2
3
4
5
6
7
Copy after login
Copy after login
Copy after login
Copy after login
server{
listen          80;
server_name    192.168.8.18  cszhi.com;
index index.html index.htm index.php;
root  /wwwroot/www.cszhi.com
charset gb2312;
access_log  logs/www.ixdba.net.access.log  main;
Copy after login

server标志定义虚拟主机开始,listen用于指定虚拟主机的服务端口,server_name用来指定IP地址或者域名,多个域名之间用空格分 开。index用于设定访问的默认首页地址,root指令用于指定虚拟主机的网页根目录,这个目录可以是相对路径,也可以是绝对路径。Charset用于 设置网页的默认编码格式。access_log用来指定此虚拟主机的访问日志存放路径,最后的main用于指定访问日志的输出格式。

2.6 location URL匹配配置
URL地址匹配是进行Nginx配置中最灵活的部分。 location支持正则表达式匹配,也支持条件判断匹配,用户可以通过location指令实现Nginx对动、静态网页进行过滤处理。使用location URL匹配配置还可以实现反向代理,用于实现PHP动态解析或者负载负载均衡。
以下这段设置是通过location指令来对网页URL进行分析处理,所有扩展名以.gif、.jpg、.jpeg、.png、.bmp、.swf结尾的静态文件都交给nginx处理,而expires用来指定静态文件的过期时间,这里是30天。

1
2
3
4
Copy after login
Copy after login
Copy after login
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  {
                root    /wwwroot/www.cszhi.com;
               expires 30d;
        }
Copy after login

以下这段设置是将upload和html下的所有文件都交给nginx来处理,当然,upload和html目录包含在/web/wwwroot/www.cszhi.com目录中。

1
2
3
4
Copy after login
Copy after login
Copy after login
 location ~ ^/(upload|html)/  {
        root    /web/wwwroot/www.cszhi.com;
        expires 30d;
        }
Copy after login

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

1
2
3
4
Copy after login
Copy after login
Copy after login
location ~ .*.php$ {
    index index.php;
    proxy_pass http://localhost:8080;
}
Copy after login

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

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

stub_status设置为“on”表示启用StubStatus的工作状态统计功能。access_log 用来指定StubStatus模块的访问日志文件。auth_basic是Nginx的一种认证机制。auth_basic_user_file用来指定认证的密码文件,由于Nginx的auth_basic认证采用的是与Apache兼容的密码文件,因此需要用Apache的htpasswd命令来生成密码文件,例如要添加一个test用户,可以使用下面方式生成密码文件:

/usr/local/apache/bin/htpasswd -c  /opt/nginx/conf/htpasswd test
Copy after login

然后输入两次密码后确认之后添加用户成功。

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

Active connections: 1
server accepts handled requests
34561 35731 354399
Reading: 0 Writing: 3 Waiting: 0
Copy after login

Active connections表示当前活跃的连接数,第三行的三个数字表示 Nginx当前总共处理了34561个连接, 成功创建次握手, 总共处理了354399个请求。最后一行的Reading表示Nginx读取到客户端Header信息数, Writing表示Nginx返回给客户端的Header信息数
,“Waiting”表示Nginx已经处理完,正在等候下一次请求指令时的驻留连接数。

在最后这段设置中,设置了虚拟主机的错误信息返回页面,通过error_page指令可以定制各种错误信息的返回页面。在默认情况下,Nginx会在主目录的html目录中查找指定的返回页面,特别需要注意的是,这些错误信息的返回页面大小一定要超过512K,否者会被ie浏览器替换为ie默认的错误页面。

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

整理自:http://ixdba.blog.51cto.com/2895551/790611

以上就介绍了Nginx安装及配置文件nginxconf详解,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template