分布式 - 服务器Nginx:基础系列之Nginx配置文件结构

1.Nginx 配置文件结构

Nginx的核心配置文件默认是放在/usr/local/nginx/conf/nginx.conf

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;

        # 访问目录/usr/local/nginx/html/index.html文件
        location / {
            root   html;
            index  index.html index.htm;
        }
        # 当后台报错500 502 503 504 时访问目录/usr/local/nginx/html/50x.html文件
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

nginx.conf 配置文件中默认有三大块:全局块、events块、http块。其中http 块中可以配置多个server块,每个server块又可以配置多个location块。

# 全局块,主要设置Nginx服务器整体运行的配置指令
指令名	指令值;  

# events块,主要设置,Nginx服务器与用户的网络连接,这一部分对Nginx服务器的性能影响较大
events {	 
    指令名	指令值;
}
# http块,是Nginx服务器配置中的重要部分,代理、缓存、日志记录、第三方模块配置...             
http {		
    指令名	指令值;
     # server块,是Nginx配置和虚拟主机相关的内容
    server {
        指令名	指令值;
        # location块,基于Nginx服务器接收请求字符串与location后面的值进行匹配,对特定请求进行处理
        location / { 
            指令名	指令值;
        }
    }
	...
}

2. Nginx 全局块的指令

01. user 指令

user指令也可以用于指定Nginx服务器worker进程的运行用户和用户组。它的语法如下:

user username [groupname];

其中,username是要指定的用户名,可以是用户名或用户ID。groupname是可选的,用于指定用户所属的用户组。如果未指定用户组,则默认使用与用户名相同的用户组。

① 修改nginx配置文件 nginx.conf,使用user指令指定nginx工作进程的用户为www:

[root@192 sbin]# cat /usr/local/nginx/conf/nginx.conf
user www;
worker_processes  1;
events {
    worker_connections  1024;
}

http {
    # ...
}

这将使Nginx工作进程以www用户的身份运行,并使用与该用户相同的用户组。

② 新建用户 www:

# 1. 测试nginx配置文件语法是否正确
[root@192 sbin]# ./nginx -t
nginx: [emerg] getpwnam("www") failed in /usr/local/nginx/conf/nginx.conf:2
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

# 2. 添加用户www
[root@192 sbin]# useradd www
[root@192 sbin]# ./nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

# 3. worker进程的默认用户名为nobody
[root@192 sbin]# ps -ef | grep nginx
root     128666      1  0 22:29 ?        00:00:00 nginx: master process ./nginx
nobody   128667 128666  0 22:29 ?        00:00:00 nginx: worker process
root     129163   2727  0 22:41 pts/0    00:00:00 grep --color=auto nginx

# 4. 重新加载nginx配置文件
[root@192 sbin]# ./nginx -s reload

# 5. worker进程的用户名为www
[root@192 sbin]# ps -ef | grep nginx
root     128666      1  0 22:29 ?        00:00:00 nginx: master process ./nginx
www      129167 128666  0 22:41 ?        00:00:00 nginx: worker process
root     129169   2727  0 22:41 pts/0    00:00:00 grep --color=auto nginx

③ 新建 /root/html/index.html 页面,并修改配置文件 nginx.conf:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
      
      
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
<p><em>I am WWW</em></p>
</body>
</html>
# 访问root/html/index.html文件
location / {
    root   /root/html;
    index  index.html index.htm;
}

④ 重新加载配置文件,并测试访问:http://192.168.38.33/,页面会报403拒绝访问的错误,因为当前用户没有访问 /root/html 目录的权限。

在这里插入图片描述

⑤ 将 index.html 文件创建到 /home/www/html/index.html,并修改配置文件nginx.conf:

[root@192 sbin]# mkdir -p /home/www/html
[root@192 html]# cp -r /root/html/ /home/www/
[root@192 sbin]# ./nginx -s reload
# 访问 /home/www/html/index.html 文件
location / {
	root   /home/www/html;
	index  index.html index.htm;
}

⑥ 重新加载配置文件,并测试访问:http://192.168.38.33/

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

# 创建用户www时,默认会创建/home/www目录,用户和用户组都是www,而/root/html目录的用户和用户组都是root
[root@192 home]# ll
drwxr-x--- 4 www www 89 91 21:06 www

因此使用user指令可以指定启动运行工作进程的用户及用户组,这样对于系统的权限访问控制的更加精细,也更加安全。

02. master_process 指令

nginx 的 master_process 指令用于控制是否启用 worker 进程。在 nginx 中,master 进程是一个管理进程,它负责启动和停止 worker 进程,并且处理一些信号和事件。如果启用了 master 进程,那么在启动 nginx 时会先启动一个 master 进程,然后由 master 进程启动 worker 进程。如果禁用了 master 进程,那么 nginx 将直接启动 worker 进程。

master_process 指令的语法如下:

master_process on | off;

当 master_process 被设置为 on 时,Nginx 将启动一个主进程来管理所有的 worker 进程。当 master_process 被设置为 off 时,Nginx 将不会启动主进程,而是直接启动一个 worker 进程来处理请求。在一些特殊的情况下,比如在容器中运行 Nginx,可能需要将 master_process 设置为 off。但是在大多数情况下,我们建议将 master_process 设置为 on,以便 Nginx 能够更好地管理 worker 进程。

[root@192 sbin]# ps -ef | grep nginx
www        1447 128666  0 23:53 ?        00:00:00 nginx: worker process
root       1488   2727  0 23:54 pts/0    00:00:00 grep --color=auto nginx
root     128666      1  0 22:29 ?        00:00:00 nginx: master process ./nginx
[root@192 sbin]# vi /usr/local/nginx/conf/nginx.conf
master_process off;
user www;
worker_processes 1;
# ...
[root@192 sbin]# ./nginx -s stop
[root@192 sbin]# ./nginx
[root@192 sbin]# ps -ef | grep nginx
root      53700      1  0 21:19 ?        00:00:00 ./nginx
root      53776   2727  0 21:20 pts/0    00:00:00 grep --color=auto nginx

03. worker_processes 指令

nginx 的 worker_processes 指令用于设置 Nginx 启动时的 worker 进程数量。每个 worker 进程都是一个独立的进程,用于处理客户端请求。

worker_processes 指令的语法如下:

worker_processes number;

其中,number 是一个整数,表示要启动的 worker 进程数量。通常情况下,建议将 number 设置为 CPU 核心数的两倍,以充分利用服务器的资源。

例如,如果服务器有 4 个 CPU 核心,可以将 worker_processes 设置为 8:

worker_processes 8;

需要注意的是,过多的 worker 进程数量可能会导致资源竞争和性能下降,因此在设置 worker_processes 时需要根据服务器的硬件配置和实际负载情况进行调整。

[root@192 sbin]# vi /usr/local/nginx/conf/nginx.conf
# master_process off;
user www;
worker_processes 2;
# ...
[root@192 sbin]# ./nginx -s stop
[root@192 sbin]# ./nginx
[root@192 sbin]# ps -ef | grep nginx
root      53904      1  0 21:23 ?        00:00:00 nginx: master process ./nginx
www       53905  53904  0 21:23 ?        00:00:00 nginx: worker process
www       53906  53904  0 21:23 ?        00:00:00 nginx: worker process
root      53910   2727  0 21:23 pts/0    00:00:00 grep --color=auto nginx

04. deamon 指令

在 Nginx 的全局块中,可以使用 daemon 指令来设置 Nginx 是否以守护进程的方式运行。守护进程是一种在后台运行的进程,它不会占用终端或控制台,并且可以在系统启动时自动启动。

daemon 指令的语法如下:

daemon on|off;

其中,on 表示以守护进程的方式运行 Nginx,off 表示以前台进程的方式运行 Nginx。默认情况下,Nginx 会以守护进程的方式运行。

如果将 Nginx 设置为以前台进程的方式运行,则在终端或控制台中启动 Nginx 的命令行将会一直占用该终端或控制台,直到手动停止 Nginx。因此,通常情况下建议将 Nginx 设置为以守护进程的方式运行。

05. pid 指令

pid 指令用来配置Nginx当前master进程的进程号ID存储的文件路径。默认为 /usr/local/nginx/logs/nginx.pid。

06. error_log 指令

Nginx 的全局块是指在 Nginx 配置文件中,位于 http 块外的指令。其中,error_log 指令用于设置 Nginx 的错误日志文件路径和日志级别。

error_log 指令的语法如下:

error_log file [level];

file 参数指定错误日志文件的路径,可以是绝对路径或相对路径。如果路径以斜杠 / 开头,则表示绝对路径;否则表示相对于 Nginx 安装目录的路径。例如:

error_log /var/log/nginx/error.log;
error_log logs/error.log;

level 参数可选,用于设置错误日志的级别。Nginx 支持以下 8 个日志级别:

  • debug:调试级别,记录详细的调试信息。
  • info:信息级别,记录一般的信息。
  • notice:注意级别,记录需要注意的信息。
  • warn:警告级别,记录警告信息。
  • error:错误级别,记录错误信息。
  • crit:严重级别,记录严重错误信息。
  • alert:警报级别,记录需要立即采取行动的信息。
  • emerg:紧急级别,记录系统崩溃等严重错误信息。

如果不指定 level 参数,则默认为 error 级别。

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

这块建议大家设置的时候不要设置成info以下的等级,因为会带来大量的磁盘I/O消耗,影响Nginx的性能。

07. include 指令

在 Nginx 的全局块中,可以使用 include 指令来引入其他配置文件,这些配置文件可以包含其他块,如 http、server、location 等。这样可以将配置文件分成多个文件,方便管理和维护。

例如,可以在 Nginx 的全局块中使用 include 指令来引入一个名为 nginx.conf.d 的目录下的所有以 .conf 结尾的文件:

include /etc/nginx/nginx.conf.d/*.conf;

这样,Nginx 就会读取该目录下的所有配置文件,并将它们合并到主配置文件中。这样做的好处是,可以将不同的配置分散到不同的文件中,便于管理和维护。

3. Nginx events块的指令

01. accept_mutex 指令

accept_mutex 指令用于控制 worker 进程在处理连接请求时的互斥锁机制。在 Nginx 中,多个 worker 进程可以同时处理连接请求,但是为了避免竞争条件,每个 worker 进程在处理连接请求时需要获取一个互斥锁,以确保同一时刻只有一个 worker 进程在处理连接请求。

accept_mutex on|off;

accept_mutex 指令的作用是控制 worker 进程在获取互斥锁时的行为。默认情况下,accept_mutex 指令的值为 on,表示启用互斥锁机制。在这种情况下,每个 worker 进程在处理连接请求时都会尝试获取互斥锁,如果获取失败,则会进入睡眠状态,等待其他 worker 进程释放互斥锁后再次尝试获取。

如果将 accept_mutex 指令的值设置为 off,则表示禁用互斥锁机制。在这种情况下,每个 worker 进程在处理连接请求时都不会尝试获取互斥锁,而是直接处理连接请求。这种方式可以提高 worker 进程的并发处理能力,但是也可能会导致竞争条件的发生,需要谨慎使用。

总之,accept_mutex 指令的作用是控制 worker 进程在处理连接请求时的互斥锁机制,可以根据实际情况进行配置。

02. multi_accept 指令

multi_accept 指令用来设置是否允许同时接收多个网络连接,如果multi_accept被禁止了,nginx一个工作进程只能同时接受一个新的连接。否则,一个工作进程可以同时接受所有的新连接。

multi_accept on|off;

但是,开启 multi_accept 会增加 CPU 的负载,因为 worker 进程需要在短时间内处理大量连接。因此,如果服务器的 CPU 资源有限,建议不要开启 multi_accept。另外,如果服务器的网络带宽较小,也不建议开启 multi_accept,因为这可能会导致连接的等待时间变长,反而降低并发处理能力。

03. worker_connections 指令

worker_connections 是一个用于配置 Nginx 服务器的指令,它用于设置每个 worker 进程可以同时处理的最大连接数。

语法如下:

worker_connections number;

默认情况下,worker_connections 的值为 512。这意味着每个 worker 进程最多可以同时处理 512 个连接。如果达到了这个限制,新的连接将被延迟处理,直到有可用的连接槽。

要根据服务器的负载和性能需求来调整 worker_connections 的值。如果服务器经常遇到连接超过默认限制的情况,可以适当增加这个值。但是要注意,过高的值可能会导致服务器资源消耗过大,因此需要根据实际情况进行调整。

04. use 指令

use 指令用来设置Nginx服务器选择哪种事件驱动来处理网络消息。

use method;

默认值根据操作系统来定,此处所选择事件处理模型是Nginx优化部分的一个重要内容,method的可选值有select/poll/epoll/kqueue等。

05. events指令配置实例

打开Nginx的配置文件 nginx.conf,添加如下配置:

events{
	accept_mutex on;
	multi_accept on;
	worker_commections 1024;
	use epoll;
}

启动测试

./nginx -t
./nginx -s reload

4. Nginx http块的指令

01. 定义 MIME Type

我们知道浏览器中可以显示的内容有HTML、XML、GIF等种类繁多的文件、媒体等资源,浏览器为了区分这些资源,就需要使用MIME Type。MIME类型是一种标准,用于指示在Web上传输的文件的类型。Nginx作为web服务器,也需要能够识别前端请求的资源类型。

在Nginx的配置文件中,默认有两行配置:

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

在上面的示例中,include 指令用于包含默认的 MIME Type 定义文件 mime.types,default_type 指令用于设置默认的 MIME Type。

例如,有些时候请求某些接口的时候需要返回指定的文本字符串或者json字符串,如果逻辑非常简单或者干脆是固定的字符串,那么可以使用nginx快速实现,这样就不用编写程序响应请求了,可以减少服务器资源占用并且响应性能非常快。

user www;
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 /get_text {
            default_type text/html;
            return 200 "This is nginx's text";
        }

        # 返回json字符串
        location /get_json{
            default_type application/json;
            return 200 '{"name":"TOM","age":18}';
        }
        
        location / {
            root   /home/www/html;
            index  index.html index.htm;
        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

测试访问:

[root@192 sbin]#  curl -i http://192.168.38.33/get_text
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 31 Aug 2023 14:51:04 GMT
Content-Type: text/html
Content-Length: 20
Connection: keep-alive

This is nginx's text 

测试访问:

[root@192 sbin]# curl -i http://192.168.38.33/get_json
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 31 Aug 2023 14:49:51 GMT
Content-Type: application/json
Content-Length: 23
Connection: keep-alive

{
    
    "name":"TOM","age":18} 

02. access.log 和 log_format 指令

nginx的access.log和error.log是用来记录服务器访问和错误信息的日志文件。

access.log 记录了每个请求到达服务器的详细信息,包括请求的时间、客户端IP地址、请求的URL、HTTP状态码、响应大小等。这个日志文件可以用来分析服务器的访问情况,比如统计访问量、分析用户行为等。

error.log 记录了服务器处理请求过程中出现的错误信息,比如请求的文件不存在、权限不足、服务器内部错误等。这个日志文件可以帮助管理员及时发现和解决服务器的问题,保证服务器的正常运行。

nginx支持对服务日志的格式、大小、输出等进行设置,需要使用到两个指令:access_log 指令和 log_format 指令。

① nginx 的 access_log 指令用于配置访问日志的输出路径和格式。位置http, server, location,它的语法如下:

access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

其中,path 指定了日志输出的路径,可以是一个文件或者是一个 Unix 域套接字。format 指定了日志的格式,可以使用预定义的格式或者自定义格式。如果指定了 buffer 参数,则表示启用缓冲,size 指定了缓冲区的大小。如果指定了 gzip 参数,则表示启用 gzip 压缩,level 指定了压缩级别。如果指定了 flush 参数,则表示定期刷新缓冲区,time 指定了刷新的时间间隔。如果指定了 if 参数,则表示只有满足条件的请求才会被记录。

② log_format 指令用于定义日志格式,位置 http,它的语法如下:

log_format name string ...;

其中,name 是日志格式的名称,string 是日志格式的字符串表示。string 中可以包含变量,变量以 $ 开头,例如 r e m o t e a d d r 表示客户端的 I P 地址, remote_addr 表示客户端的 IP 地址, remoteaddr表示客户端的IP地址,request_time 表示请求处理时间。预定义的变量可以在 nginx 的官方文档中找到,也可以自定义变量。定义好日志格式后,可以在 access_log 指令中使用该格式。

③ nginx配置文件中默认的服务器访问日志路径和格式:

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;

    server {
        # ...
    }
}

查看服务器的访问日志:

[root@192 sbin]# tail -f /usr/local/nginx/logs/access.log
192.168.38.1 - - [30/Aug/2023:23:23:38 +0800] "GET / HTTP/1.1" 403 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
192.168.38.1 - - [30/Aug/2023:23:23:38 +0800] "GET /favicon.ico HTTP/1.1" 403 555 "http://192.168.38.33/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"

④ nginx配置文件中自定义服务器访问日志路径和格式:

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

    log_format my_log_format '========>$remote_addr=======>';
    access_log  logs/access.log  my_log_format;

    server {
	  # ...
    }
}

查看服务器的访问日志:

[root@192 sbin]# tail -f /usr/local/nginx/logs/access.log
========>192.168.38.1=======>
========>192.168.38.1=======>

03. sendfile 指令

用来设置Nginx服务器是否使用sendfile()传输文件,该属性可以大大提高Nginx处理静态资源的性能

sendfile 指令用于在发送文件时提高性能。它允许 Nginx 将文件数据直接从磁盘发送到网络套接字,而无需将数据从内核空间复制到用户空间,从而减少了 CPU 和内存的使用。

在 Nginx 中,sendfile 指令默认是开启的。可以通过在 nginx.conf 文件中设置 sendfile 指令来控制其行为。例如,可以使用以下指令来禁用 sendfile:

sendfile off;

需要注意的是,sendfile 指令只在发送静态文件时才有效,对于动态生成的内容,它不起作用。此外,sendfile 指令在某些情况下可能会导致问题,例如在某些操作系统上,它可能会导致文件描述符泄漏。因此,在使用 sendfile 指令时,需要仔细测试和评估其性能和稳定性。

04. keepalive_timeout 指令

keepalive_timeout 指令用于设置客户端与服务器之间的 keep-alive 连接超时时间。当客户端与服务器之间的连接处于 keep-alive 状态时,客户端可以在同一连接上发送多个请求,而无需每次都建立新的连接。这可以减少连接建立和关闭的开销,提高性能。

keepalive_timeout 指令的语法如下:

keepalive_timeout timeout;

其中,timeout 参数指定 keep-alive 连接的超时时间,单位为秒。如果在指定的时间内没有新的请求到达,连接将被关闭。

为什么要使用keepalive?

我们都知道HTTP是一种无状态协议,客户端向服务端发送一个TCP请求,服务端响应完毕后断开连接。如果客户端向服务端发送多个请求,每个请求都需要重新创建一次连接,效率相对来说比较多,使用keepalive模式,可以告诉服务器端在处理完一个请求后保持这个TCP连接的打开状态,若接收到来自这个客户端的其他请求,服务端就会利用这个未被关闭的连接,而不需要重新创建一个新连接,提升效率,但是这个连接也不能一直保持,这样的话,连接如果过多,也会是服务端的性能下降,这个时候就需要我们进行设置其的超时时间。

例如,以下配置将 keep-alive 连接的超时时间设置为 60 秒:

keepalive_timeout 60s;

05. keepalive_requests 指令

keepalive_requests 指令用于设置在一个 keep-alive 连接中处理的最大请求数量。当客户端与 Nginx 建立 keep-alive 连接时,可以在同一个连接中发送多个 HTTP 请求,以减少连接建立和关闭的开销,提高性能。

该指令的语法如下:

keepalive_requests number;

其中,number 表示在一个 keep-alive 连接中处理的最大请求数量。默认值为 100。

当一个 keep-alive 连接中的请求数量达到 keepalive_requests 指定的值时,Nginx 会自动关闭该连接,以避免连接过长时间占用资源。可以通过增加该值来提高性能,但需要注意,过大的值可能会导致连接过长时间占用资源,从而影响服务器的性能。

5. Nginx 配置为文件案例解析

需求如下:

  • 访问 http://192.168.200.133:8081/server1/location1,访问的是:index_sr1_location1.html。
  • 访问 http://192.168.200.133:8081/server1/location2,访问的是:index_sr1_location2.html。
  • 访问 http://192.168.200.133:8082/server2/location1,访问的是:index_sr2_location1.html。
  • 访问 http://192.168.200.133:8082/server2/location2,访问的是:index_sr2_location2.html。
  • 如果访问的资源不存在,返回自定义的404页面。
  • 将/server1和/server2的配置使用不同的配置文件,将文件放到/home/www/conf.d目录下,然后使用include合并。
  • 为/server1和/server2各自创建一个访问日志文件。

① 创建相关文件:

[root@192 sbin]# tree /home/www
/home/www
├── conf.d
│   ├── server1.conf
│   └── server2.conf
└── myweb
    ├── 404.html
    ├── server1
    │   ├── location1
    │   │   └── index_sr1_location1.html
    │   ├── location2
    │   │   └── index_sr1_location2.html
    │   └── logs
    │       └── access.log
    └── server2
        ├── location1
        │   └── index_sr2_location1.html
        ├── location2
        │   └── index_sr2_location2.html
        └── logs
            └── access.log

[root@192 home]# cat /home/www/myweb/404.html
<h1>This is 404.html in myweb</h1>
[root@192 home]# cat /home/www/myweb/server1/location1/index_sr1_location1.html
<h1>This is index_server1_location1.html</h1>
[root@192 home]# cat /home/www/myweb/server1/location2/index_sr1_location2.html
<h1>This is index_server1_location2.html</h1>
[root@192 home]# cat /home/www/myweb/server2/location1/index_sr2_location1.html
<h1>This is index_server2_location1.html</h1>
[root@192 home]# cat /home/www/myweb/server2/location2/index_sr2_location2.html
<h1> This is index_server2_location2.html</h1>

② 配置文件 /user/local/nginx/nginx.conf:

[root@192 conf]# vi nginx.conf
# 配置允许运行Nginx工作进程的用户和用户组
user www;
# 配置运行Nginx进程生成的worker进程数
worker_processes 2;
# 配置Nginx服务器运行对错误日志存放的路径
error_log logs/error.log;
# 配置Nginx服务器允许时记录Nginx的master进程的PID文件路径和名称
pid logs/nginx.pid;
 
events{
    
    
	# 设置Nginx网络连接序列化
	accept_mutex on;
	# 设置Nginx的worker进程是否可以同时接收多个请求
	multi_accept on;
	# 设置Nginx的worker进程最大的连接数
	worker_connections 1024;
	# 设置Nginx使用的事件驱动模型
	use epoll;
}

http{
    
    
	# 定义MIME-Type
	include mime.types;
	default_type application/octet-stream;
    
	# 配置允许使用sendfile方式运输
	sendfile on;
    
	# 配置连接超时时间
	keepalive_timeout 65;
    
	# 配置请求处理日志格式
	log_format server1 '===>server1 access log';
	log_format server2 '===>server2 access log';
    
	include /home/www/conf.d/*.conf;
}

[root@192 sbin]# ./nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

[root@192 sbin]# ./nginx -s reload 

③ 配置文件 /home/www/conf.d/server1.conf:

[root@192 conf.d]# cat server1.conf
server{
    # 配置监听端口和主机名称
    listen 8081;
    server_name localhost;

    # 配置请求处理日志存放路径
    access_log /home/www/myweb/server1/logs/access.log server1;

    # 配置错误页面
    error_page 404 /404.html;

    # 配置处理/server1/location1请求的location
    location /server1/location1{
        root /home/www/myweb;
        index index_sr1_location1.html;
    }
    # 配置处理/server1/location2请求的location
    location /server1/location2{
        root /home/www/myweb;
        index index_sr1_location2.html;
    }
    # 配置错误页面转向
    location = /404.html {
        root /home/www/myweb;
        index 404.html;
    }
}

④ 配置文件 /home/www/conf.d/server2.conf:

[root@192 conf.d]# cat server2.conf
server{
    # 配置监听端口和主机名称
    listen 8082;
    server_name localhost;

    # 配置请求处理日志存放路径
    access_log /home/www/myweb/server2/logs/access.log server2;

    # 配置错误页面,对404.html做了定向配置
    error_page 404 /404.html;

    # 配置处理/server1/location1请求的location
    location /server2/location1{
        root /home/www/myweb;
        index index_sr2_location1.html;
    }
    # 配置处理/server2/location2请求的location
    location /server2/location2{
        root /home/www/myweb;
        index index_sr2_location2.html;
    }
    # 配置错误页面转向
    location = /404.html {
        root /home/www/myweb;
        index 404.html;
    }
}

⑤ 访问测试:可以看到报错403 Forbidden

在这里插入图片描述

查看 nginx 的错误日志,可以看到用户没有读取目录 /home/www/myweb/server1/location1的权限

[root@192 sbin]# tail -f /usr/local/nginx/logs/error.log
2023/09/01 22:05:36 [error] 113845#0: *6 open() "/home/www/myweb/server1/location1" failed (13: Permission denied), client: 192.168.38.33, server: localhost, request: "GET /server1/location1 HTTP/1.1", host: "192.168.38.33:8081"

⑥ 查看运行Nginx进程的用户和访问目录的权限,确认Nginx进程用户是否具有访问该目录的权限:

[root@192 sbin]# ps aux | grep nginx
root     113496  0.0  0.0  20684  1472 ?        Ss   21:55   0:00 nginx: master process ./nginx
www      113844  0.0  0.0  21076  1400 ?        S    22:04   0:00 nginx: worker process
www      113845  0.0  0.0  21076  1644 ?        S    22:04   0:00 nginx: worker process
root     114050  0.0  0.0 112824   980 pts/0    R+   22:08   0:00 grep --color=auto nginx

[root@192 sbin]# ll  /home/www/myweb/server1/location1
-rwxr-x--- 1 root root 46 91 21:04 index_sr1_location1.html

# 给home/www/目录下的目录和文件添加用户名和用户组www
[root@192 home]# sudo chgrp -R www /home/www/
[root@192 home]# sudo chown -R www /home/www/
[root@192 home]# cd /home/www/myweb/server2/location1
[root@192 location1]# ll
-rwxrwxrwx 1 www www 46 91 21:05 index_sr2_location1.html

⑦ 运行测试:

[root@192 sbin]# curl  http://192.168.38.33:8081/server1/location2/
<h1>This is index_server1_location2.html</h1>

[root@192 sbin]# curl  http://192.168.38.33:8081/server1/location1/
<h1>This is index_server1_location1.html</h1>

[root@192 sbin]# curl  http://192.168.38.33:8081/server2/location1/
<h1>This is 404.html in myweb</h1>

[root@192 sbin]# curl  http://192.168.38.33:8082/server2/location1/
<h1>This is index_server2_location1.html</h1>

[root@192 sbin]# curl  http://192.168.38.33:8082/server2/location2/
<h1> This is index_server2_location2.html</h1>

6. Nginx 配置成系统服务

把Nginx应用服务设置成为系统服务,方便对Nginx服务的启动和停止等相关操作,具体实现步骤:

① 在/usr/lib/systemd/system目录下添加 nginx.service,内容如下:

[root@192 conf]# cat /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx web service
Documentation=http://nginx.org/en/docs/
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=default.target

② 添加完成后如果权限有问题需要进行权限设置:

[root@192 conf]# chmod 755 /usr/lib/systemd/system/nginx.service

③ 使用系统命令来操作Nginx服务:

# 启动nginx服务
[root@192 conf]# systemctl start nginx
Warning: nginx.service changed on disk. Run 'systemctl daemon-reload' to reload units.
[root@192 conf]# systemctl daemon-reload
[root@192 conf]# systemctl start nginx
# 查看nginx服务状态
[root@192 conf]# systemctl status nginx
● nginx.service - nginx web service
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since 五 2023-09-01 23:08:54 CST; 2min 24s ago
     Docs: http://nginx.org/en/docs/
 Main PID: 116647 (nginx)
   CGroup: /system.slice/nginx.service
           ├─116647 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
           └─116648 nginx: worker process

9月 01 23:08:54 192.168.38.33 systemd[1]: Starting nginx - high performance web server...
9月 01 23:08:54 192.168.38.33 systemd[1]: New main PID 7638 does not exist or is a zombie.
9月 01 23:08:54 192.168.38.33 systemd[1]: Started nginx - high performance web server.
# 停止nginx服务
[root@192 conf]# systemctl stop nginx
[root@192 conf]# systemctl status nginx
● nginx.service - nginx web service
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: http://nginx.org/en/docs/

828 22:00:10 192.168.38.33 systemd[1]: Failed to parse PID from file /usr/local/nginx/logs/nginx.pid: Invalid argument
828 22:00:10 192.168.38.33 systemd[1]: Started nginx - web server.
828 22:23:13 192.168.38.33 systemd[1]: nginx.service: main process exited, code=killed, status=9/KILL
828 22:23:13 192.168.38.33 systemd[1]: Unit nginx.service entered failed state.
828 22:23:13 192.168.38.33 systemd[1]: nginx.service failed.
9月 01 23:08:54 192.168.38.33 systemd[1]: Starting nginx - high performance web server...
9月 01 23:08:54 192.168.38.33 systemd[1]: New main PID 7638 does not exist or is a zombie.
9月 01 23:08:54 192.168.38.33 systemd[1]: Started nginx - high performance web server.
9月 01 23:11:27 192.168.38.33 systemd[1]: Stopping nginx web service...
9月 01 23:11:27 192.168.38.33 systemd[1]: Stopped nginx web service.
# 重新启动nginx服务
[root@192 conf]# systemctl restart nginx
# 重新加载nginx配置文件
[root@192 conf]# systemctl reload nginx
# 开机启动nginx服务
[root@192 conf]# systemctl enable nginx
Created symlink from /etc/systemd/system/default.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.

7. Nginx 命令配置到系统环境

经过前面的操作,我们会发现,如果想要启动、关闭或重新加载nginx配置文件,都需要先进入到nginx的安装目录的sbin目录,然后使用nginx的二级制可执行文件来操作,相对来说操作比较繁琐,这块该如何优化?

① 修改 /etc/profile 文件,在文件最后一行添加:

export PATH=$PATH:/usr/local/nginx/sbin
[root@192 conf]# vi /etc/profile
[root@192 conf]# source /etc/profile

② 测试在任何目录下执行nginx的相关命令:

[root@192 conf]# systemctl status nginx
● nginx.service - nginx web service
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since 五 2023-09-01 23:11:41 CST; 7min ago
     Docs: http://nginx.org/en/docs/
 Main PID: 116813 (nginx)
   CGroup: /system.slice/nginx.service
           ├─116813 nginx: master process /usr/local/nginx/sbin/nginx
           ├─116826 nginx: worker process
           └─116827 nginx: worker process

9月 01 23:11:41 192.168.38.33 systemd[1]: Starting nginx web service...
9月 01 23:11:41 192.168.38.33 nginx[116810]: nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
9月 01 23:11:41 192.168.38.33 nginx[116810]: nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
9月 01 23:11:41 192.168.38.33 systemd[1]: Failed to parse PID from file /usr/local/nginx/logs/nginx.pid: Invalid argument
9月 01 23:11:41 192.168.38.33 systemd[1]: Started nginx web service.
9月 01 23:11:48 192.168.38.33 systemd[1]: Reloading nginx web service.
9月 01 23:11:48 192.168.38.33 systemd[1]: Reloaded nginx web service.

猜你喜欢

转载自blog.csdn.net/qq_42764468/article/details/132613407
今日推荐