Distributed - Server Nginx: Nginx configuration file structure of the basic series

1.Nginx configuration file structure

The core configuration file of Nginx is placed by default /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;
        }
    }
}

There are three blocks in the nginx.conf configuration file by default: global block, events block, and http block. Multiple server blocks can be configured in the http block, and multiple location blocks can be configured in each server block.

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

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

2. Nginx global block instructions

01. user command

The user directive can also be used to specify the running user and user group of the Nginx server worker process. Its syntax is as follows:

user username [groupname];

Among them, username is the username to be specified, which can be a username or user ID. groupname is optional and is used to specify the user group to which the user belongs. If no user group is specified, the user group with the same user name is used by default.

① Modify the nginx configuration file nginx.conf and use the user directive to specify the user of the nginx working process as www:

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

http {
    # ...
}

This will make the Nginx worker process run as the www user and use the same user group as that user.

② Create a new user 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

③ Create a new /root/html/index.html page and modify the configuration file 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;
}

④ Reload the configuration file and test access: http://192.168.38.33/. The page will report a 403 access denied error because the current user does not have permission to access the /root/html directory.

Insert image description here

⑤ Create the index.html file /home/www/html/index.htmland modify the configuration file 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;
}

⑥ Reload the configuration file and test access: http://192.168.38.33/

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

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

Therefore, you can use the user command to specify the user and user group that starts and runs the work process, so that the permission access control of the system is more refined and safer.

02. master_process command

The master_process directive of nginx is used to control whether to enable the worker process. In nginx, the master process is a management process, which is responsible for starting and stopping worker processes, and handling some signals and events. If the master process is enabled, a master process will be started when nginx is started, and then the worker process will be started by the master process. If the master process is disabled, nginx will start the worker process directly.

The syntax of the master_process directive is as follows:

master_process on | off;

When master_process is set to on, Nginx will start a master process to manage all worker processes. When master_process is set to off, Nginx will not start the main process, but directly start a worker process to handle the request. In some special cases, such as running Nginx in a container, you may need to set master_process to off. But in most cases, we recommend setting master_process to on so that Nginx can better manage worker processes.

[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 directive

The worker_processes directive of nginx is used to set the number of worker processes when Nginx starts. Each worker process is an independent process used to handle client requests.

The syntax of the worker_processes directive is as follows:

worker_processes number;

Among them, number is an integer, indicating the number of worker processes to be started. Normally, it is recommended to set number to twice the number of CPU cores to fully utilize the server's resources.

For example, if the server has 4 CPU cores, worker_processes can be set to 8:

worker_processes 8;

It should be noted that too many worker processes may cause resource competition and performance degradation, so setting worker_processes needs to be adjusted based on the server's hardware configuration and actual load conditions.

[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 command

In the global block of Nginx, you can use the daemon directive to set whether Nginx runs as a daemon process. A daemon is a process that runs in the background, does not occupy a terminal or console, and can be started automatically when the system starts.

The syntax of the daemon directive is as follows:

daemon on|off;

Among them, on means running Nginx as a daemon process, and off means running Nginx as a foreground process. By default, Nginx runs as a daemon.

If Nginx is set to run as a foreground process, the command line to start Nginx in the terminal or console will occupy the terminal or console until Nginx is stopped manually. Therefore, it is usually recommended to set Nginx to run as a daemon process.

05. pid command

The pid directive is used to configure the file path where the process ID of the current master process of Nginx is stored. The default is /usr/local/nginx/logs/nginx.pid.

06. error_log command

The global block of Nginx refers to the instructions located outside the http block in the Nginx configuration file. Among them, the error_log directive is used to set the error log file path and log level of Nginx.

The syntax of the error_log directive is as follows:

error_log file [level];

The file parameter specifies the path to the error log file, which can be an absolute or relative path. If the path starts with a slash /, it represents an absolute path; otherwise, it represents a path relative to the Nginx installation directory. For example:

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

The level parameter is optional and is used to set the level of the error log. Nginx supports the following 8 log levels:

  • debug: debugging level, recording detailed debugging information.
  • info: information level, records general information.
  • notice: Attention level, records information that needs attention.
  • warn: warning level, record warning information.
  • error: error level, record error information.
  • crit: Severity level, recording serious error information.
  • alert: Alert level, recording information that requires immediate action.
  • emerg: Emergency level, records serious error messages such as system crash.

If the level parameter is not specified, the default is error level.

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

It is recommended that you do not set it to a level below info when setting this, because it will cause a lot of disk I/O consumption and affect the performance of Nginx.

07. include directive

In the global block of Nginx, you can use the include directive to introduce other configuration files. These configuration files can contain other blocks, such as http, server, location, etc. In this way, the configuration file can be divided into multiple files to facilitate management and maintenance.

For example, you can use the include directive in the global block of Nginx to introduce all files ending with .conf in a directory named nginx.conf.d:

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

In this way, Nginx will read all configuration files in this directory and merge them into the main configuration file. The advantage of this is that different configurations can be dispersed into different files for easier management and maintenance.

3. Instructions for Nginx events block

01. accept_mutex command

The accept_mutex directive is used to control the mutex lock mechanism of the worker process when processing connection requests. In Nginx, multiple worker processes can process connection requests at the same time, but in order to avoid race conditions, each worker process needs to acquire a mutex when processing connection requests to ensure that only one worker process is processing connection requests at the same time.

accept_mutex on|off;

The accept_mutex directive is used to control the behavior of the worker process when acquiring a mutex lock. By default, the value of the accept_mutex directive is on, which means the mutex lock mechanism is enabled. In this case, each worker process will try to acquire the mutex when processing a connection request. If the acquisition fails, it will enter a sleep state and wait for other worker processes to release the mutex before trying to acquire again.

If the value of the accept_mutex directive is set to off, it means that the mutex lock mechanism is disabled. In this case, each worker process does not attempt to acquire the mutex when handling a connection request, but instead handles the connection request directly. This method can improve the concurrent processing capability of the worker process, but it may also lead to race conditions and needs to be used with caution.

In short, the accept_mutex directive is used to control the mutex lock mechanism of the worker process when processing connection requests, and can be configured according to the actual situation.

02. multi_accept directive

The multi_accept directive is used to set whether to allow multiple network connections to be received at the same time. If multi_accept is disabled, one nginx worker process can only accept one new connection at the same time. Otherwise, a worker process can accept all new connections simultaneously.

multi_accept on|off;

However, turning on multi_accept will increase the CPU load because the worker process needs to handle a large number of connections in a short period of time. Therefore, if the server's CPU resources are limited, it is recommended not to enable multi_accept. In addition, if the server's network bandwidth is small, it is not recommended to turn on multi_accept, because this may cause the connection waiting time to become longer and reduce concurrent processing capabilities.

03. worker_connections directive

worker_connections is a directive used to configure the Nginx server. It is used to set the maximum number of connections that each worker process can handle simultaneously.

The syntax is as follows:

worker_connections number;

By default, the value of worker_connections is 512. This means that each worker process can handle up to 512 connections simultaneously. If this limit is reached, new connections will be delayed until a connection slot becomes available.

The value of worker_connections should be adjusted based on the load and performance requirements of the server. If the server often encounters connections exceeding the default limit, you can increase this value appropriately. However, be aware that too high a value may cause excessive consumption of server resources, so it needs to be adjusted according to the actual situation.

04. use command

The use directive is used to set which event driver the Nginx server chooses to process network messages.

use method;

The default value is determined by the operating system. The event processing model selected here is an important part of the Nginx optimization part. Optional values ​​for method include select/poll/epoll/kqueue, etc.

05. Events directive configuration example

Open the Nginx configuration file nginx.conf and add the following configuration:

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

Start testing

./nginx -t
./nginx -s reload

4. Nginx http block instructions

01. Define MIME Type

We know that the content that can be displayed in the browser includes a wide variety of files, media and other resources such as HTML, XML, GIF and so on. In order to distinguish these resources, the browser needs to use MIME Type. A MIME type is a standard used to indicate the type of files transferred over the web. As a web server, Nginx also needs to be able to identify the resource type requested by the front end.

In the Nginx configuration file, there are two lines of configuration by default:

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

In the above example, the include directive is used to include the default MIME Type definition file mime.types, and the default_type directive is used to set the default MIME Type.

For example, sometimes when requesting certain interfaces, you need to return a specified text string or json string. If the logic is very simple or simply a fixed string, you can use nginx to quickly implement it, so you don't have to write a program to respond to the request. It can reduce server resource usage and provide very fast response performance.

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

Test access:

[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 

Test access:

[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 and log_format directives

nginx's access.log and error.log are log files used to record server access and error information.

access.log records detailed information about each request arriving at the server, including the time of the request, client IP address, requested URL, HTTP status code, response size, etc. This log file can be used to analyze server access, such as counting visits, analyzing user behavior, etc.

error.log records error information that occurs when the server processes requests, such as the requested file does not exist, insufficient permissions, internal server errors, etc. This log file can help administrators discover and solve server problems in a timely manner to ensure the normal operation of the server.

nginx supports setting the format, size, output, etc. of service logs. Two instructions are required: the access_log instruction and the log_format instruction.

① The access_log directive of nginx is used to configure the output path and format of the access log. Position http, server, location, its syntax is as follows:

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

Among them, path specifies the path of the log output, which can be a file or a Unix domain socket. format specifies the format of the log, which can use a predefined format or a custom format. If the buffer parameter is specified, buffering is enabled, and size specifies the size of the buffer. If the gzip parameter is specified, it means that gzip compression is enabled, and level specifies the compression level. If the flush parameter is specified, it means that the buffer is refreshed regularly, and time specifies the refresh interval. If the if parameter is specified, it means that only requests that meet the conditions will be recorded.

② The log_format directive is used to define the log format and location http. Its syntax is as follows:

log_format name string ...;

Among them, name is the name of the log format, and string is the string representation of the log format. The string can contain variables, which start with $. For example, remoteaddr represents the IP address of the client, and remote_addr represents the IP address of the client.remoteadd r represents the IP address of the client , and request_time represents the request processing time. Predefined variables can be found in the official documentation of nginx, and variables can also be customized. After defining the log format, you can use the format in the access_log directive.

③ Default server access log path and format in nginx configuration file:

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 {
        # ...
    }
}

View the server's access log:

[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"

④ Customize the server access log path and format in the nginx configuration file:

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 {
	  # ...
    }
}

View the server's access log:

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

03. sendfile command

Used to set whether the Nginx server uses sendfile() to transfer files. This attribute can greatly improve the performance of Nginx in processing static resources.

The sendfile directive is used to improve performance when sending files. It allows Nginx to send file data directly from disk to network sockets without copying data from kernel space to user space, thus reducing CPU and memory usage.

In Nginx, the sendfile directive is enabled by default. Its behavior can be controlled by setting the sendfile directive in the nginx.conf file. For example, sendfile can be disabled using the following directive:

sendfile off;

It should be noted that the sendfile directive only works when sending static files, it does not work for dynamically generated content. Additionally, the sendfile directive may cause problems in certain situations, such as on some operating systems where it may cause a file descriptor leak. Therefore, when using the sendfile directive, its performance and stability need to be carefully tested and evaluated.

04. keepalive_timeout command

The keepalive_timeout directive is used to set the keep-alive connection timeout between the client and the server. When the connection between the client and the server is in the keep-alive state, the client can send multiple requests on the same connection without establishing a new connection each time. This reduces the overhead of connection establishment and closing and improves performance.

The syntax of the keepalive_timeout directive is as follows:

keepalive_timeout timeout;

Among them, the timeout parameter specifies the timeout time of the keep-alive connection, in seconds. If no new requests arrive within the specified time, the connection will be closed.

Why use keepalive?

We all know that HTTP is a stateless protocol. The client sends a TCP request to the server, and the server disconnects after completing the response. If the client sends multiple requests to the server, each request needs to re-create a connection, which is relatively more efficient. Using the keepalive mode, you can tell the server to keep the TCP connection open after processing a request. If it receives other requests from this client, the server will use this unclosed connection instead of re-creating a new connection to improve efficiency. However, this connection cannot be maintained forever. In this case, if there are too many connections, It will also cause the performance of the server to decrease. At this time, we need to set its timeout.

For example, the following configuration sets the timeout for keep-alive connections to 60 seconds:

keepalive_timeout 60s;

05. keepalive_requests directive

The keepalive_requests directive is used to set the maximum number of requests processed in a keep-alive connection. When the client establishes a keep-alive connection with Nginx, it can send multiple HTTP requests in the same connection to reduce the overhead of connection establishment and closing and improve performance.

The syntax of this command is as follows:

keepalive_requests number;

Among them, number represents the maximum number of requests processed in a keep-alive connection. The default value is 100.

When the number of requests in a keep-alive connection reaches the value specified by keepalive_requests, Nginx will automatically close the connection to prevent the connection from occupying resources for a long time. You can improve performance by increasing this value, but be aware that too large a value may cause the connection to occupy resources for a long time, thus affecting server performance.

5. Nginx configuration as file case analysis

The requirements are as follows:

  • When accessing http://192.168.200.133:8081/server1/location1, the accessed page is: index_sr1_location1.html.
  • When accessing http://192.168.200.133:8081/server1/location2, the accessed page is: index_sr1_location2.html.
  • When accessing http://192.168.200.133:8082/server2/location1, the accessed page is: index_sr2_location1.html.
  • When accessing http://192.168.200.133:8082/server2/location2, the accessed page is: index_sr2_location2.html.
  • If the accessed resource does not exist, a customized 404 page is returned.
  • Use different configuration files for the configuration of /server1 and /server2, put the files in the /home/www/conf.d directory, and then use include to merge them.
  • Create an access log file each for /server1 and /server2.

① Create relevant files:

[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>

② Configuration file/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 

③ Configuration file/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;
    }
}

④ Configuration file/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;
    }
}

⑤ Access test: You can see the error 403 Forbidden

Insert image description here

Looking at the nginx error log, you can see that the user does not have permission to read the directory /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"

⑥ Check the user running the Nginx process and the permissions to access the directory to confirm whether the Nginx process user has permission to access the directory:

[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

⑦ Run the test:

[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. Configure Nginx as a system service

Set the Nginx application service as a system service to facilitate related operations such as starting and stopping the Nginx service. Specific implementation steps:

/usr/lib/systemd/systemAdd nginx.service in the directory with the following content:

[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

② After the addition is completed, if there is a problem with the permissions, you need to set the permissions:

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

③ Use system commands to operate Nginx service:

# 启动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. Configure Nginx commands to the system environment

After the previous operations, we will find that if we want to start, close or reload the nginx configuration file, we need to first enter the sbin directory of the nginx installation directory, and then use the nginx secondary executable file to operate. Relatively speaking, It is said that the operation is relatively cumbersome. How to optimize this area?

① Modify the /etc/profile file and add: in the last line of the file:

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

② Test the execution of nginx related commands in any directory:

[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.

Guess you like

Origin blog.csdn.net/qq_42764468/article/details/132613407