Home  >  Article  >  Operation and Maintenance  >  Nginx installation and configuration example analysis

Nginx installation and configuration example analysis

WBOY
WBOYforward
2023-05-17 23:28:04741browse

nginx is a free, open source, high-performance http server and reverse proxy server; it is also an imap, pop3, and smtp proxy server; nginx can be used as an http server for website publishing and processing. In addition, nginx can Implementation of load balancing as a reverse proxy.

Here is a brief introduction to nginx from three aspects

Reverse proxy load balancing nginx features 1. Reverse proxy

About the proxy

Speaking of agency, first we need to clarify a concept. The so-called agent is a representative and a channel;

At this time, two roles are designed, one is the agent role, and the other is the target role. The process in which the agent character accesses the target character through this agent to complete some tasks is called the agent operation process; just like a specialty store in life, a customer goes to an adidas store to buy a pair of shoes. This specialty store is the agent, and the agent role is the adidas manufacturer. The target The role is the user

Nginx installation and configuration example analysis

Forward proxy

Before talking about the reverse proxy, let’s take a look at the forward proxy. Forward proxy It is also the most common proxy model that everyone comes into contact with. We will talk about the processing model of forward proxy from two aspects, and explain what forward proxy is from the software aspect and the life aspect.

Nowadays In a network environment, if we need to access certain foreign websites due to technical needs, you will find that we cannot access a certain foreign website through a browser. At this time, everyone may use an operation fq to access it. , the main method of fq is to find a proxy server that can access foreign websites. We send the request to the proxy server, and the proxy server accesses the foreign website, and then passes the accessed data to us!

The above proxy mode is called forward proxy. The biggest feature of forward proxy is that the client is very clear about the server address it wants to access; the server only knows which proxy server the request comes from, but not which specific one it comes from. Client; forward proxy mode blocks or hides real client information.

Nginx installation and configuration example analysis

Reverse proxy

Understanding what a forward proxy is, let’s continue to look at how to deal with reverse proxy, for example The number of visitors to a certain treasure website in my country has exploded every day. A single server is far from being able to satisfy the people's growing desire to purchase. At this time, a familiar term appeared: distributed deployment; also It solves the problem of limiting the number of visitors by deploying multiple servers; most functions of a certain website are also implemented directly using nginx for reverse proxy, and after encapsulating nginx and other components, it has a fancy name: tengine

So how does reverse proxy implement distributed cluster operations? Let’s first look at a schematic diagram:

Nginx installation and configuration example analysis

Through the above As you can see clearly from the diagram, after receiving the requests sent by multiple clients to the server, the nginx server distributes them to the back-end business processing server for processing according to certain rules. At this time, the source of the request is clear, that is, the client, but it is not clear which server handles the request. nginx plays the role of a reverse proxy

Reverse proxy, mainly used for In the case of distributed deployment of server clusters, the reverse proxy hides server information!

Project scenario

Normally, when we operate the actual project, the forward proxy and the reverse proxy are likely to exist in an application scenario. Proxy the client's request to access the target server. The target server is a reverse single-interest server, which reversely proxies multiple real business processing servers. The specific topology diagram is as follows:

Nginx installation and configuration example analysis

2. Load balancing

We have clarified the concept of the so-called proxy server, so next, nginx plays the reverse role What is the role of the proxy server? What rules does it use to distribute requests? Can the distribution rules be controlled for different project application scenarios?

The number of requests sent by the client and received by the nginx reverse proxy server mentioned here is what we call the load

The number of requests is distributed to different servers according to certain rules The processing rule is a balancing rule

So~The process of distributing requests received by the server according to the rules is called load balancing.

In the actual project operation process, load balancing has two types: hardware load balancing and software load balancing. Hardware load balancing is also called hard load, such as f5 load balancing, which is relatively expensive and costly, but the data is stable and safe. There is a very good guarantee for performance, etc. Only companies such as China Mobile and China Unicom will choose hard load operations; more companies will choose to use software load balancing for cost reasons. Software load balancing uses existing technology. A message queue distribution mechanism implemented in combination with host hardware

Nginx installation and configuration example analysis

The load balancing scheduling algorithm supported by nginx is as follows:

weight wheel Query (default): The received requests are assigned to different back-end servers one by one in order. Even if a back-end server goes down during use, nginx will automatically remove the server from the queue, and the request acceptance status will not change. be affected in any way. In this way, a weight value (weight) can be set for different back-end servers to adjust the allocation rate of requests on different servers; the larger the weight data, the greater the probability of being allocated to the request; the weight value, It is mainly adjusted for different back-end server hardware configurations in actual working environments.

ip_hash: Each request is matched according to the hash result of the initiating client's IP. Under this algorithm, a client with a fixed IP address will always access the same back-end server, which is also solved to a certain extent. Solve the problem of session sharing in cluster deployment environment.

fair: Intelligent adjustment of the scheduling algorithm, dynamic and balanced allocation based on the time from request processing to response of the back-end server. Servers with short response times and high processing efficiency have a high probability of being assigned to requests, and servers with long response times have high processing efficiency. Low servers are assigned fewer requests; a scheduling algorithm that combines the advantages of the first two. However, it should be noted that nginx does not support the fair algorithm by default. If you want to use this scheduling algorithm, please install the upstream_fair module

url_hash: allocate requests according to the hash result of the accessed URL, and the URL of each request will point to the following A server with a fixed end can improve caching efficiency when nginx is used as a static server. It should also be noted that nginx does not support this scheduling algorithm by default. If you want to use it, you need to install the nginx hash software package

nginx installation 1. Windows installation

Official website download address:

https://nginx.org/en/download.html

As shown in the figure below, download the corresponding version of the nginx compressed package and unzip it to the folder where the software is stored on your computer.

Nginx installation and configuration example analysis

After the decompression is completed, the file directory The structure is as follows:

Nginx installation and configuration example analysis

Start nginx

1) Directly double-click nginx.exe in this directory to start the nginx server

2 ) The command line is included in the folder. Executing the nginx command will also directly start the nginx server

d:/resp_application/nginx-1.13.5> nginx

Nginx installation and configuration example analysis

Access nginx

Open the browser and enter the address: http://localhost, visit the page, the following page appears to indicate successful access

Nginx installation and configuration example analysis

Stop nginx

Command line to enter the nginx root directory, execute the following command, stop Server:

# 强制停止nginx服务器,如果有未处理的数据,丢弃
d:/resp_application/nginx-1.13.5> nginx -s stop

# 优雅的停止nginx服务器,如果有未处理的数据,等待处理完成之后停止
d:/resp_application/nginx-1.13.5> nginx -s quit

Nginx installation and configuration example analysis

2. Ubuntu installation

Follow the normal software installation method and install directly through the following command:

$ sudo apt-get install nginx

Nginx installation and configuration example analysis

The installation is complete. The /usr/sbin/ directory is the directory where the nginx command is located. The /etc/nginx/ directory is all the nginx configuration files, which are used to configure the nginx server and load balancing. Waiting for information

Check whether the nginx process is started

$ ps -ef|grep nginx

nginx will automatically create the corresponding number of processes based on the number of cores of the current host's cpu (the current ubuntu host is configured with 2 cores and 4 threads)

Nginx installation and configuration example analysis

Note: The service process started here is actually 4 processes, because when the nginx process is started, it will be accompanied by a daemon process to protect the official process from being terminated abnormally; if Once the daemon process is terminated and the nginx inheritance is terminated, the process will be automatically restarted.

The daemon process is generally called the master process, and the business process is called the worker process

Start the nginx server command

Directly executing nginx will start the server according to the default configuration file Start

$ nginx

Nginx installation and configuration example analysis Stop

nginx service command

和windows系统执行过程一样,两种停止方式

$ nginx -s stop
or
$ nginx -s quit

Nginx installation and configuration example analysis 

重新启动加载

同样也可以使用命令reopen和reload来重新启动nginx或者重新加载配合着文件。

3. mac os安装

直接通过brew进行nginx的安装,或者下载tar.gz压缩包都是可以的。

直接通过brew进行安装

brew install nginx

安装完成后,后续的命令操作,服务器的启动、进程查看、服务器的停止、服务器的重启已经文件加载命令都是一致的。

nginx配置

nginx是一个功能非常强大的web服务器加反向代理服务器,同时又是邮件服务器等等

在项目使用中,使用最多的三个核心功能是反向代理、负载均衡和静态服务器

这三个不同的功能的使用,都跟nginx的配置密切相关,nginx服务器的配置信息主要集中在nginx.conf这个配置文件中,并且所有的可配置选项大致分为以下几个部分

main                # 全局配置

events {              # nginx工作模式配置

}

http {                # http设置
....

server {            # 服务器主机配置
....
location {          # 路由配置
....
}

location path {
....
}

location otherpath {
....
}
}

server {
....

location {
....
}
}

upstream name {          # 负载均衡配置
....
}
}

如上述配置文件所示,主要由6个部分组成:

main:用于进行nginx全局信息的配置 events:用于nginx工作模式的配置 http:用于进行http协议信息的一些配置 server:用于进行服务器访问信息的配置 location:用于进行访问路由的配置 upstream:用于进行负载均衡的配置 main模块

观察下面的配置代码

# user nobody nobody;
worker_processes 2;
# error_log logs/error.log
# error_log logs/error.log notice
# error_log logs/error.log info
# pid logs/nginx.pid
worker_rlimit_nofile 1024;

上述配置都是存放在main全局配置模块中的配置项

user用来指定nginx worker进程运行用户以及用户组,默认nobody账号运行 worker_processes指定nginx要开启的子进程数量,运行过程中监控每个进程消耗内存(一般几m~几十m不等)根据实际情况进行调整,通常数量是cpu内核数量的整数倍 error_log定义错误日志文件的位置及输出级别【debug / info / notice / warn / error / crit】 pid用来指定进程id的存储文件的位置 worker_rlimit_nofile用于指定一个进程可以打开最多文件数量的描述 event 模块

上干货

event {
worker_connections 1024;
multi_accept on;
use epoll;
}

上述配置是针对nginx服务器的工作模式的一些操作配置

worker_connections 指定最大可以同时接收的连接数量,这里一定要注意,最大连接数量是和worker processes共同决定的。 multi_accept 配置指定nginx在收到一个新连接通知后尽可能多的接受更多的连接 use epoll 配置指定了线程轮询的方法,如果是linux2.6+,使用epoll,如果是bsd如mac请使用kqueue http模块

作为web服务器,http模块是nginx最核心的一个模块,配置项也是比较多的,项目中会设置到很多的实际业务场景,需要根据硬件信息进行适当的配置,常规情况下,使用默认配置即可!

http {
##
# 基础配置
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# ssl证书配置
##
ssl_protocols tlsv1 tlsv1.1 tlsv1.2; # dropping sslv3, ref: poodle
ssl_prefer_server_ciphers on;
##
# 日志配置
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# gzip 压缩配置
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript
text/xml application/xml application/xml+rss text/javascript;

##
# 虚拟主机配置
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

1) 基础配置

sendfile on:配置on让sendfile发挥作用,将文件的回写过程交给数据缓冲去去完成,而不是放在应用中完成,这样的话在性能提升有有好处
tc_nopush on:让nginx在一个数据包中发送所有的头文件,而不是一个一个单独发
tcp_nodelay on:让nginx不要缓存数据,而是一段一段发送,如果数据的传输有实时性的要求的话可以配置它,发送完一小段数据就立刻能得到返回值,但是不要滥用哦
keepalive_timeout 10:给客户端分配连接超时时间,服务器会在这个时间过后关闭连接。一般设置时间较短,可以让nginx工作持续性更好
client_header_timeout 10:设置请求头的超时时间
client_body_timeout 10:设置请求体的超时时间
send_timeout 10:指定客户端响应超时时间,如果客户端两次操作间隔超过这个时间,服务器就会关闭这个链接
limit_conn_zone $binary_remote_addr zone=addr:5m :设置用于保存各种key的共享内存的参数,
limit_conn addr 100: 给定的key设置最大连接数
server_tokens:虽然不会让nginx执行速度更快,但是可以在错误页面关闭nginx版本提示,对于网站安全性的提升有好处哦
include /etc/nginx/mime.types:指定在当前文件中包含另一个文件的指令
default_type application/octet-stream:指定默认处理的文件类型可以是二进制
type_hash_max_size 2048:混淆数据,影响三列冲突率,值越大消耗内存越多,散列key冲突率会降低,检索速度更快;值越小key,占用内存较少,冲突率越高,检索速度变慢

2) 日志配置

access_log logs/access.log:设置存储访问记录的日志
error_log logs/error.log:设置存储记录错误发生的日志

3) ssl证书加密

ssl_protocols:指令用于启动特定的加密协议,nginx在1.1.13和1.0.12版本后默认是ssl_protocols sslv3 tlsv1 tlsv1.1 tlsv1.2,tlsv1.1与tlsv1.2要确保openssl >= 1.0.1 ,sslv3 现在还有很多地方在用但有不少被攻击的漏洞。
ssl prefer server ciphers:设置协商加密算法时,优先使用我们服务端的加密套件,而不是客户端浏览器的加密套件

4) 压缩配置

gzip 是告诉nginx采用gzip压缩的形式发送数据。这将会减少我们发送的数据量。
gzip_disable 为指定的客户端禁用gzip功能。我们设置成ie6或者更低版本以使我们的方案能够广泛兼容。
gzip_static 告诉nginx在压缩资源之前,先查找是否有预先gzip处理过的资源。这要求你预先压缩你的文件(在这个例子中被注释掉了),从而允许你使用最高压缩比,这样nginx就不用再压缩这些文件了(想要更详尽的gzip_static的信息,请点击这里)。
gzip_proxied 允许或者禁止压缩基于请求和响应的响应流。我们设置为any,意味着将会压缩所有的请求。
gzip_min_length 设置对数据启用压缩的最少字节数。如果一个请求小于1000字节,我们最好不要压缩它,因为压缩这些小的数据会降低处理此请求的所有进程的速度。
gzip_comp_level 设置数据的压缩等级。这个等级可以是1-9之间的任意数值,9是最慢但是压缩比最大的。我们设置为4,这是一个比较折中的设置。
gzip_type 设置需要压缩的数据格式。上面例子中已经有一些了,你也可以再添加更多的格式。

5) 文件缓存配置

open_file_cache 打开缓存的同时也指定了缓存最大数目,以及缓存的时间。我们可以设置一个相对高的最大时间,这样我们可以在它们不活动超过20秒后清除掉。
open_file_cache_valid 在open_file_cache中指定检测正确信息的间隔时间。
open_file_cache_min_uses 定义了open_file_cache中指令参数不活动时间期间里最小的文件数。
open_file_cache_errors 指定了当搜索一个文件时是否缓存错误信息,也包括再次给配置中添加文件。我们也包括了服务器模块,这些是在不同文件中定义的。如果你的服务器模块不在这些位置,你就得修改这一行来指定正确的位置。

server模块

srever模块配置是http模块中的一个子模块,用来定义一个虚拟访问主机,也就是一个虚拟服务器的配置信息

server {
listen    80;
server_name localhost  192.168.1.100;
root    /nginx/www;
index    index.php index.html index.html;
charset    utf-8;
access_log  logs/access.log;
error_log  logs/error.log;
......
}

核心配置信息如下:

server:一个虚拟主机的配置,一个http中可以配置多个server

server_name:用力啊指定ip地址或者域名,多个配置之间用空格分隔

root:表示整个server虚拟主机内的根目录,所有当前主机中web项目的根目录

index:用户访问web网站时的全局首页

charset:用于设置www/路径中配置的网页的默认编码格式

access_log:用于指定该虚拟主机服务器中的访问记录日志存放路径

error_log:用于指定该虚拟主机服务器中访问错误日志的存放路径

location模块

location模块是nginx配置中出现最多的一个配置,主要用于配置路由访问信息

在路由访问信息配置中关联到反向代理、负载均衡等等各项功能,所以location模块也是一个非常重要的配置模块

基本配置

location / {
root  /nginx/www;
index  index.php index.html index.htm;
}

location /:表示匹配访问根目录

root:用于指定访问根目录时,访问虚拟主机的web目录

index:在不指定访问具体资源时,默认展示的资源文件列表

反向代理配置方式

通过反向代理代理服务器访问模式,通过proxy_set配置让客户端访问透明化

location / {
proxy_pass http://localhost:8888;
proxy_set_header x-real-ip $remote_addr;
proxy_set_header host $http_host;
}

uwsgi配置

wsgi模式下的服务器配置访问方式

location / {
include uwsgi_params;
uwsgi_pass localhost:8888
}

upstream模块

upstream模块主要负责负载均衡的配置,通过默认的轮询调度方式来分发请求到后端服务器

简单的配置方式如下

upstream name {
ip_hash;
server 192.168.1.100:8000;
server 192.168.1.100:8001 down;
server 192.168.1.100:8002 max_fails=3;
server 192.168.1.100:8003 fail_timeout=20s;
server 192.168.1.100:8004 max_fails=3 fail_timeout=20s;
}

核心配置信息如下

ip_hash:指定请求调度算法,默认是weight权重轮询调度,可以指定

server host:port:分发服务器的列表配置

-- down: Indicates that the host suspends service

-- max_fails: Indicates the maximum number of failures, and the service is suspended when the maximum number of failures exceeds

-- fail_timeout: Indicates that if the request fails to be accepted, the service will be suspended. Re-initiate the request after the specified time

The above is the detailed content of Nginx installation and configuration example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete