[Nginx] Detailed explanation of Nginx configuration files, this article lets you understand Nginx configuration files

1. nginx

Nginx (engine x) is a high-performance HTTP and reverse proxy web server, and also provides IMAP/POP3/SMTP services.

2. nginx configuration file directory

  • fastcgi.conf: store fastcgi related configuration
  • fastcgi.conf.default: the original backup file of fastcgi.conf for restoring
  • fastcgi_params: fastcgi related parameter files
  • fastcgi_params.default: the original backup file of fastcgi_params, used to restore
  • koi-utf: code conversion mapping file
  • koi-win: code conversion mapping file
  • mime.types: store the type of media resources, for example: xml, html, css
  • mime.types.default: original backup file of mime.types, used for restore
  • nginx.conf: nginx default main configuration file
  • nginx.conf.default: the original backup file of nginx.conf for restoring
  • scgi_params: Same as fastcgi_params, which server variables are passed
  • scgi_params.default: original backup file of scgi_params, used for restore
  • uwsgi_params: The communication protocol between the server and the server application, which specifies how to forward the request to the application and return
  • uwsgi_params.default: original backup file of uwsgi_params, used for restore

3. Common configuration of nginx configuration file (nginx.conf)

The nginx configuration file is mainly divided into six areas

  • main: global settings (scope global)
  • events: nginx working mode
  • http: http settings
    • upstream: load balancing server settings
      • server: Host settings (a server node is a virtual machine)
        • location : URL configuration

1. The main main configuration area, corresponding to the functions of the nginx core module

#main区域,主配置区域,全局的

#定义 www 运行的用户和用户组,建议新建 www 用户和用户组 
user  www;

#启动工作进程数数量,一般设置和CPU核心数一致
worker_processes  1;    

#全局错误日志定义类型.【debug|info|notice|warm|error|crit】
error_log  logs/error.log;   
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#进程pid文件位置
#pid        logs/nginx.pid;    

3.2 events area

#events区域
events {
    
    
    #一个进程可以产生多少个工作的连接,nginx的最大并发访问量
    worker_connections  1024; 
    
    #使用epoll 模型,异步IO 处理模型,epoll 模型没有1024 的限制,并发发访问量特别快
    use epoll;    
}

3.3 Common configuration parameters of nginx core module


http {
    
    
    #包含媒体资源类型的文件,调用mime.types文件.
    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;
    
    #作为web服务器的时候打开sendfile加快静态文件传输
    sendfile        on;
    
    #在开启了sendfile的情况下,合并请求后统一发送给客户端。
    tcp_nopush     on;    
    
    #在开启了keepalived模式下的连接是否启用TCP_NODELAY选项,当为off时,延迟0.2s发送,默认On时,不延迟发送,立即发送用户相应报文。
    tcp_nodelay  off;
    
    #长连接超时时间,单位是秒
    keepalive_timeout  65;   
    
    #设置了每个散列桶占用的内存大小
    types_hash_max_size 2048;
    
    #开启压缩功能.
    gzip  on;
    
    #压缩的缓冲区大小
    gzip_buffers 16 8k;
    
	#压缩级别,默认为1
    gzip_comp_level 6;
    
	# 禁止那些浏览器压缩功能
	gzip_disable "MSIE [1-6].(?!.*SV1)";
   
	#小于128字节不压缩
	gzip_min_length 128;
    
    #只对 那些http版本进行压缩 默认 1.1 
	gzip_http_version 1.1;
    
 
    #用来配置虚拟主机,每一个server 段都是一个虚拟主机
    server {
    
    
        #监听80 端口,可以做基于端口的虚拟主机,listen 后面 IP加端口就是基于IP的虚拟主机
        listen       80; 
        
        #用来定义虚拟主机名称即域名; 支持*通配符,支持~起始字符做正则表达式匹配
        server_name  localhost;
        
		#设置编码格式,默认是俄语格式,可以改为utf-8
        charset utf-8;
        
 		#定义虚拟主机的访问日志
        access_log  /var/log/nginx/host.access.log  main;
 
        ###localtion 匹配段,用于匹配
        location / {
    
    
            #设置 WEB 资源路径映射,用于指明用户请求的 uri 所对应的本地文件系统上的文档目录.
            root   /usr/share/nginx/html;
            
            #默认资源设置
            index  index.html index.htm;
        }
          
 		#当客户端访问出错时定义返回的页面, 跳转404页面 /404.html;   
        #error_page  404              
        # 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 api scripts to Apache listening on xxx.xxx.xxx.xxx
        location /api/ {
    
    
            
            # webapi服务的IP地址和端口,内网地址
            proxy_pass         http://xxx.xxx.xxx.xxx;
            proxy_set_header   Host              $host;
            proxy_set_header   X-Real-IP         $remote_addr;
            proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Proto $scheme;
            proxy_set_header   X-Forwarded-Port  $server_port;
            
			#此指令设置nginx能处理的最大请求主体大小
            client_max_body_size 200m;
            #接超时时间
            proxy_read_timeout  500;
        }

      
        # 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.conf;
        #}
 
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
    
    
        #    deny  all;
        #}
    }
 

4. How to configure nginx front end

Add an html file in the nginx directory for static file hosting, port 8080

Copy the front-end project to the /nginx/html folder
Add a server node configuration in the configuration file (/nginx/conf/nginx.conf) under nginx to the domain name to be configured

server {
    
    
        #监听的端口,
        listen       8080;
    
        #此处localhost可改为要访问的域名或者ip地址
        server_name  localhost;
    
        #编码
        charset utf-8;

        #access_log  logs/host.access.log  main;
    
        #error_page  404              /404.html;

        location / {
    
    
            #nginx下HTML文件夹,访问上述域名时会检索此文件夹下的文件进行访问
            root   html;
            #输入网址(server_name:port)后,默认的访问页面
            index  index.html index.htm;
        }
}

After the configuration is correct, restart nginx (service nginx restart)

service nginx restart

test access

5. nginx proxy backend API

If there are cross-domain issues. Proxy configuration can be added (replaced //xxx.xxx.xxx.xxx with /api.)

location /api/ {
    
    
    # webapi服务的IP地址和端口,内网地址
    proxy_pass         http://xxx.xxx.xxx.xxx;
    
    #重定义发往后端服务器的请求头
    proxy_set_header   Host              $host;
    proxy_set_header   X-Real-IP         $remote_addr;
    proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   X-Forwarded-Port  $server_port;

    client_max_body_size 200m;
    proxy_read_timeout  500;
}

6.nginx view service status

Nginx needs to be configured to enable Nginx Status to view the running status of the server

open nginx status

server {
    
    
        #监听的端口,
        listen       8080;
        
        ···

        location /status {
    
    
            stub_status on;
            access_log off;            
        }
    
        ····
}

The command to restart nginx is relatively simple, please restart your nginx according to your environment.
Open the status page and enter the address of nginx in the browser: xxx.xxx.xxx.xxx/status to view...

Active connections: 4 
server accepts handled requests
 4 4 15 
Reading: 0 Writing: 1 Waiting: 3 

Active connections: 4 
表示Nginx正在处理的活动连接数4个。

server accepts handled requests
 4 4 15 
第一个server表示Nginx启动到现在共处理了4个连接
第二个accepts表示Nginx.启动到现在共成功创建4次握手
第三个handled requests表示总共处理了15次请求

Reading: 0 Writing: 1 Waiting: 3 
Reading:读取到客户端的Header信息数
Writing:返回给客户端Header信息数
Waiting:已经处理完正在等候下一次请求指令的驻留链接(开启keep-alive的情况下,这个值等于Active-(Reading+Writing)

7. How does nginx view logs

1. nginx view access log

  1. Enable access logging using the access_log directive in the server section or HTTP.

By default, access logs are defined in the Nginx configuration file. Therefore, access logs for all virtual hosts will be stored in the same configuration file.

http {
    
    
      ...
      #自定义访问日志中的格式
      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  /var/log/nginx/access.log;
      #关闭指令
      #access_log off
      ...
}

2. It is recommended to separate access logs for all virtual hosts by logging into new separate files.

http {
    
    
      ...
      ...
      #自定义访问日志中的格式
      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  /var/log/nginx/access.log;
   
       server {
    
    
                  listen 80;
                  Server_name example.com
                  access_log  /var/log/nginx/example.access.log;
                  ...
                  ...
                }
}

3. After making all changes to nginx's configuration, reload nginx and run the tail command

vim /var/log/nginx/example.access.log

2. nginx view error log

If nginx suddenly stops running or fails to work properly, it will log all events in the error log. So using the error log you can find more details. It also logs warnings, but cannot identify problems that have occurred.
The nginx error log has different security levels, and the following security levels can be used in the error log:
emerg: used for emergency messages when the system is unstable
alert: generate alert messages for serious problems.
crit: Used for immediate processing in emergency situations.
error: An error may have occurred while processing the page.
warn: for warning messages
notice: a notification log that you can also ignore.
info: For information, message
debug: Points to the error location for debug information.

enable error logging

http {
    
    
       ...
       ...
       error_log  /var/log/nginx/error_log;
       #关闭指令
       #error_log off
    
       server {
    
    
                listen 80;
                server_name example1.com;
                    error_log  /var/log/nginx/example1.error_log  warn;
                        ...
       }
       server {
    
    
                listen 8081;
                server_name example2.com;
                    error_log  /var/log/nginx/example2.error_log  debug;
                        ...
   }
}

nginx -t Check whether there is an error in Nginx, and restart after no error is reported

nginx -t 

reload nginx

service nginx restart

Then run the page and report an error directly into the error log for viewing

vim var/log/nginx/example1.error_log  

Guess you like

Origin blog.csdn.net/ihero/article/details/132355115