current position:Home>Detailed explanation of the installation and basic use of Nginx

Detailed explanation of the installation and basic use of Nginx

2022-09-23 01:48:53big cat and little yellow

高性能的http服务器/反向代理服务器.官方测试支持5万并发,CPU、The consumption of memory, etc. is low and the operation is stable

使用场景

  • Http服务器.
    Nginx可以单独提供Http服务,As a server for static web pages.
  • 虚拟主机.
    Multiple websites can be virtualized on one server.
  • 反向代理与负载均衡.
    Nginx做反向代理,The load can be shared among multiple servers,It will not cause a high load of a server to go down or a server to be very idle.

Linux环境安装Nginx

官方网站

  1. 安装依赖包
# SSL功能需要openssl库,直接通过yum安装: 
yum install openssl

# gzip模块需要zlib库,直接通过yum安装: 
yum install zlib

# rewrite模块需要pcre库,直接通过yum安装: 
yum install pcre

Or install the above three dependencies directly,命令:

yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel

在这里插入图片描述在这里插入图片描述

  1. 创建一个用于存放Nginx的文件夹
    在这里插入图片描述

  2. 下载Nginxtarpackage to its own folder.
    命令:wget http://nginx.org/download/nginx-1.22.0.tar.gz
    在这里插入图片描述
    在这里插入图片描述

  3. 解压tar包.
    命令:tar -xvf nginx-1.22.0.tar.gz
    在这里插入图片描述

  4. 安装模块.
    进入Nginx目录,执行命令:
    ./configure
    在这里插入图片描述

  5. 安装Nginx
    命令:make
    make install

  6. 安装完成


Nginx常用命令

进入Nginx安装目录下的sbin目录

  1. 启动
    命令:./nginx
    在这里插入图片描述

  2. 查看是否启动
    命令:ps ef | grep nginx
    在这里插入图片描述

  3. 关闭
    命令:nginx -s stop或者nginx -s quit

  4. 重启,重新加载配置文件
    命令:nginx -s reload


防火墙配置

  1. 查看所有打开的端口
    命令:firewall-cmd --zone=public --list-ports
    在这里插入图片描述

  2. 开放指定端口号
    命令:firewall -cmd --zone=public --add-port=80/tcp --permanent
    在这里插入图片描述

  3. 重新载入
    命令:firewall-cmd --reload
    在这里插入图片描述


Nginx无法重启

描述:Restarting nginx daemon: nginxnginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory) nginx not running

解决:Nginx -cThe parameter specifies the configuration file to resolve
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf


Nginx访问

【IP + 端口号 80默认不显示】
在这里插入图片描述


Nginx基本配置说明

  • main:全局设置.Affects all other settings.
  • server:主机服务相关设置,主要用于指定虚拟主机域名、IP和端口号等.
  • location:URL匹配特定位置后的设置,反向代理、Settings related to content tampering.
  • upstream:Upstream server settings and load balancing related settings.

Nginx常用功能配置

反向代理
server {
    
    listen 80;
    server_name wh.test.com;
    location /api {
    
        # 反向代理的地址
        # 所有 /api The interface access is proxied to 7075 端口
            例如:wh.test.com/api/login.do -> http://localhost:7050/login.do
        proxy_pass http://localhost:7075/;
    }
}

访问控制:黑名单
server {
    
    location / {
    
        # 屏蔽单个ip访问
        deny 172.16.60.220;
        
        # 屏蔽所有ip
        deny all;
        
        # 允许ip访问
        allow 172.16.60.220;
    }
}

在这里插入图片描述
在这里插入图片描述


负载均衡:轮询

Each request will be allocated to different servers one by one in chronological order,If there is a service downtime,NginxDowntime servers will be eliminated,Proceed to assign request.

If one of the servers is too stressed,出现延迟,Will affect all user requests under this server.

http {
      
    upstream test.com {
      
        server 192.168.10.1:8081;  
        server 192.168.10.2:8082;  
        server 192.168.10.3:8083;  
    }  
    server {
      
        location /test {
      
            proxy_pass  http://test.com;  
        }  
    }  
}

负载均衡:权重

理想状态下,10次请求中有6次请求了8081,1次请求了8082,3次请求了8083

http {
      
    upstream test.com {
      
        server 192.168.10.1:8081 weight=6;  
        server 192.168.10.2:8082 weight=1;  
        server 192.168.10.3:8083 weight=3;  
    }  
    server {
      
        location /test {
      
            proxy_pass  http://test.com;  
        }  
    }  
}

负载均衡:Hash

计算方式:abs(客户端ip.hash())%服务器数量.

客户端的IP地址是唯一不变的.所以,通过hash算法计算出ipThe hash value corresponding to the address,Perform a pattern operation on the number of servers by the hash code value.This keeps the server that each client accesses the same.Because of the characteristics of the hash algorithm hash,It can also be approximated as an even distribution.

http {
      
    upstream test.com {
      
        ip_hash;
        server 192.168.10.1:8081;  
        server 192.168.10.2:8082;  
        server 192.168.10.3:8083;  
    }  
    server {
      
        location /test {
      
            proxy_pass  http://test.com;  
        }  
    }  
}

负载均衡:最小连接数

Load balancing based on least connections,NginxThe request will be sent to the server that currently handles the least number of requests,Used to share the pressure between the various servers.

http {
      
    upstream test.com {
      
        least_conn;
        server 192.168.10.1:8081;  
        server 192.168.10.2:8082;  
        server 192.168.10.3:8083;  
    }  
    server {
      
        location /test {
      
            proxy_pass  http://test.com;  
        }  
    }  
}

gzip压缩

开启gzip压缩可以减少http传输过程中文件的大小.It can greatly improve the access speed of the website.

gzip  on; # 开启gzip 压缩
gzip_types; # 要采用 gzip 压缩的 MIME 文件类型,其中 text/html 被系统强制启用
gzip_static on; # 默认 off,该模块启用后,Nginx 首先检查是否存在请求静态文件的 gz 结尾的文件,如果有则直接返回该 .gz 文件内容
gzip_proxied expired no-cache no-store private auth; # 默认 off,nginx 做为反向代理时启用,用于设置启用或禁用从代理服务器上收到相应内容 gzip 压缩
gzip_buffers 16 8k; # 获取多少内存用于缓存压缩结果,16 8k 表示以 8k*16 为单位获得
gzip_min_length 1k; # 允许压缩的页面最小字节数,页面字节数从 header 头中的 Content-Length 中进行获取.默认值是 0,不管页面多大都压缩.建议设置成大于 1k 的字节数,小于 1k 可能会越压越大
gzip_comp_level 4; # gzip 压缩比,压缩级别是 1-9,1 压缩级别最低,9 最高,级别越高压缩率越大,压缩时间越长,建议 4-6
gzip_http_version 1.0; # 默认 1.1,启用 gzip 所需的 HTTP 最低版本
gzip_vary off; # 用于在响应消息头中添加 Vary:Accept-Encoding,使代理服务器根据请求头中的 Accept-Encoding 识别是否启用 gzip 压缩
gzip_disable "MSIE [1-6]\.";// 指定哪些不需要 gzip 压缩的浏览器

Http静态资源服务器
server {
      
  listen       80;  
  server_name  localhost;  

  #后台管理
  location /handadmin{
    
      alias  /opt/home/handbook/dist/;
      index index.html;
  }  
}

动静分离

Nginx设置expiresAccess to the cache can be specified.设置之后,The user will only access the cache in the browser at the specified time,而不会去请求Nginx

# 静态请求
location ~ \.(gif|jpg|jpeg|png|bmp|swf|css|js) {
      
    root /usr/local/dist;  
    expires 10h; # 设置过期时间为10小时  
}  

# 动态请求
location ~ \.(do) {
      
    proxy_pass  127.0.0.1:8081;  
} 

图片防盗链

Prevent other websites from using external links to access server pictures

server {
      
    listen 8081;  
    server_name  localhost;  

    # 图片防盗链  
    location ~* \.(gif|jpg|jpeg|png|bmp|swf) {
      
        valid_referers none blocked server_names ~\.google\. ~\.baidu\. *.qq.com;  
        # 只允许本机 IP 外链引用,将百度和谷歌也加入白名单有利于 SEO  
        if (invalid_referer){
      
            return 403;  
        }  
    }  
} 

适配PC

根据用户请求的user-agent来判断返回PC还是H5

server {  
    listen 80;  
    server_name test.com;  

    location / {  
     root  /usr/local/app/pc; # pc 的 html 路径 
        if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {  
            root /usr/local/app/mobile; # mobile 的 html 路径 
        }  
        index index.html;  
    }  
} 

设置二级域名
server {  
    listen 80;  
    server_name admin.test.com; // 二级域名 

    location / {  
        root  /usr/local/app/admin; # 二级域名的 html 路径 
        index index.html;  
    }  
} 

配置Https
server{  
    listen 443 ssl http2; # 这里还启用了 http/2.0
    ssl_certificate /etc/letsencrypt/live/test.com/fullchain.pem; # 证书文件地址 
    ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem; # 私钥文件地址 
    server_name test.com www.test.com; # 证书绑定的域名 
}

配置Http转Https
server {  
    listen      80;  
    server_name  www.test.com;  

    # 单域名重定向  
    if (host = 'www.test.com'){  
        return 301 https://www.test1.com;  
    }  

    # 全局非 https 协议时重定向  
    if (scheme != 'https') {  
        return 301 https://server_name$request_uri;  
    }  

    # 或者全部重定向  
    return 301 https://server_name$request_uri;  
}

禁止指定user_agent
# http_user_agent 为浏览器标识  
# 禁止 user_agent 为baidu、360和sohu,~*表示不区分大小写匹配  
if (http_user_agent ~* 'baidu|360|sohu') {
      
    return 404;
}  

# 禁止 Scrapy 等工具的抓取  
if (http_user_agent ~* (Scrapy|Curl|HttpClient)) {
      
    return 403; 
}

#### 请求过滤
#### 根据请求类型过滤

# 非指定请求全返回 403  
if ( request_method !~ ^(GET|POST|HEAD) ) {
      
    return 403;  
}  

copyright notice
author[big cat and little yellow],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/266/202209230139433335.html

Random recommended