跳至主要內容

nginx

wangdx大约 10 分钟

nginx 安装配置

#1.下载nginx nginx-1.24.0.tar.gz
/srv/ftp/nginx-1.24.0.tar.gz
#解压文件
tar zxvf /srv/ftp/nginx-1.24.0.tar.gz -C /usr/local/
##依赖安装

################### pcre #######################
#安装gcc编译器及其环境,包含gcc, gdb, make等
apt -y install build-essential
#下载pcre安装包
wget http://downloads.sourceforge.net/project/pcre/pcre/8.35/pcre-8.35.tar.gz
#解压
tar xzvf /srv/ftp/pcre-8.35.tar.gz -C /usr/local/
#进入解压目录,编译安装
cd /usr/local/pcre-8.35
./configure
make && make install
############### openssl  ##################
apt-get -y install openssl libssl-dev zlib1g-dev
############### zlib  ##################
apt-get -y install zlib1g-dev


cd /src/ftp/
wget https://zlib.net/current/zlib.tar.gz
tar xzvf /srv/ftp/zlib.tar.gz -C /usr/local/
cd /usr/local/zlib-1.3.1/
./configure
make && make install
################ libxml2/libxslt  libxml2-dev#################
apt-get -y install libxml2-dev libxml2  libxslt1-dev libgd-dev libgeoip1 libgeoip-dev geoip-bin
################ gd   #################
apt-get -y install libgd-dev
################ gd   #################
sudo apt -y install libgeoip1 libgeoip-dev geoip-bin


#进入解压目录,编译安装
cd /usr/local/nginx-1.24.0
./configure --prefix=/usr/local/nginx  \
    --with-threads \
    --with-file-aio \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_addition_module \
    --with-http_xslt_module=dynamic \
    --with-http_image_filter_module=dynamic \
    --with-http_geoip_module=dynamic \
    --with-http_sub_module \
    --with-http_dav_module \
    --with-http_flv_module \
    --with-http_mp4_module \
    --with-http_gunzip_module \
    --with-http_gzip_static_module \
    --with-http_auth_request_module \
    --with-http_random_index_module \
    --with-http_secure_link_module \
    --with-http_degradation_module \
    --with-http_slice_module \
    --with-http_stub_status_module \
    --with-stream=dynamic \
    --with-stream_ssl_module \
    --with-stream_realip_module \
    --with-stream_geoip_module=dynamic \
    --with-stream_ssl_preread_module \
    --with-compat  \
    --with-pcre-jit

make && make install

/usr/local/nginx/sbin/nginx -s stop
/usr/local/nginx/sbin/nginx -s quit
#防火墙配置
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
#添加进系统服务
# 新建系统服务文件#
vim /etc/systemd/system/nginx.service
#重新加载系统控制单元
systemctl daemon-reload
#启动Tomcat服务:
systemctl start nginx
#关闭Tomcat服务:
systemctl stop nginx
#重启Tomcat服务:
systemctl restart nginx
#查看Tomcat状态:
systemctl status nginx
#开启Tomcat自启动:
systemctl enable nginx.service
#关闭Tomcat自启动:
systemctl disable nginx.service
详情
[Unit]
Description=nginx - web server
After=network.target remote-fs.target nss-lookup.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 -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecQuit=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
user  root;

worker_processes  2;

error_log  logs/error.log;

pid        logs/nginx.pid;

events {
    # 默认使用epoll
  	use epoll;
    worker_connections  10240;
}


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/httpaccess.log  main;
    sendfile        on;
    tcp_nopush      on;

    keepalive_timeout  65;
    #开启gzip压缩功能
    gzip  on;
    #限制最小压缩,小于1字节文件不会压缩
    gzip_min_length 1;
    gzip_buffers 4 16k;
    #定义压缩的级别(压缩比,文件越大,压缩越多,但是CPU使用会越多)
    gzip_comp_level 3;
    #定义压缩文件类型
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/json;
    gzip_static on;
    gzip_proxied expired no-cache no-store private auth;
    gzip_disable "MSIE [1-6]\.";
    server {
        listen       8990;
        server_name  localhost;

        access_log  logs/service18.access.log  combined;

        location /vue {
            root   /www/project/vue/vue2/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        location /docs {
            alias /www/project/doc/env/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        location /java_docs {
            alias /www/project/doc/java/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
          root   /usr/share/nginx/html;
        }
    }
    server {
        listen       6066;
        server_name  localhost;

        access_log  logs/service6066.access.log  combined;

        location / {
            root   /www/project/vue2-admin/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
          root   /usr/share/nginx/html;
        }
    }

}

nginx 完全卸载

1.自定义安装

#1.关闭nginx
systemctl stop nginx
#未配置
/usr/local/nginx/sbin/nginx -s stop
#查看当前进程 是否全部关闭nginx
ps -aux | grep nginx
#还是存在
kill -9 89755 4555 4265 2325....
#查找nginx相关文件
find / -name nginx*
#删除上面查询目录
rm -rf file
  1. apt 安装
#1.1 删除nginx,–purge包括配置文件
sudo apt-get --purge remove nginx
#1.2 自动移除全部不使用的软件包
sudo apt-get autoremove
#1.3 罗列出与nginx相关的软件
dpkg --get-selections|grep nginx
#1.4 删除1.3查询出与nginx有关的软件
sudo apt-get --purge remove nginx
sudo apt-get --purge remove nginx-common
sudo apt-get --purge remove nginx-cor
#2.查看nginx正在运行的进程,如果有就kill掉
ps -ef |grep nginx
#3.kill nginx进程
sudo kill  -9  7875 7876 7877 7879
#4.全局查找与nginx相关的文件
sudo  find  /  -name  nginx*
#5.依依删除4列出的所有文件
#6.6. 再次重装
sudo apt-get update
sudo apt-get install nginx

nginx 多配置文件

#1.新建文件夹放置要引入的配置文件
mkdir /usr/local/nginx/config/

Nginx 正则表达式

1.nginx 常用的正则表达式

^ :匹配输入字符串的起始位置
$ :匹配输入字符串的结束位置
* :匹配前面的字符零次或多次。如“ol*”能匹配“o”及“ol”、“oll”
+ :匹配前面的字符一次或多次。如“ol+”能匹配“ol”及“oll”、“olll”,但不能匹配“o”
? :匹配前面的字符零次或一次,例如“do(es)?”能匹配“do”或者“does”,”?”等效于”{0,1}”
. :匹配除“\n”之外的任何单个字符,若要匹配包括“\n”在内的任意字符,请使用诸如“[.\n]”之类的模式
\ :将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用。如“\n”匹配一个换行符,而“\$”则匹配“$”
\d :匹配纯数字[0-9]   \s :空白符    \w :任意单词字符包括下划线[A-Za-z0-9_]
{n} :重复 n 次
{n,} :重复 n 次或更多次
{n,m} :重复 n 到 m 次
[] :定义匹配的字符范围
[c] :匹配单个字符 c
[a-z] :匹配 a-z 小写字母的任意一个
[a-zA-Z0-9] :匹配所有大小写字母或数字
() :表达式的开始和结束位置
| :或运算符

2.location

location 大致可以分为三类

精准匹配:location = / {...}
一般匹配:location / {...}
正则匹配:location ~ / {...}

location 常用的匹配规则

= :进行普通字符精确匹配,也就是完全匹配。
^~ :表示普通字符匹配。使用前缀匹配。如果匹配成功,则不再匹配其它 正则匹配location。
~ :区分大小写的匹配。
~* :不区分大小写的匹配。
!~ :区分大小写的匹配取非。
!~* :不区分大小写的匹配取非。

location 优先级

首先精确匹配 =
其次前缀匹配 ^~
其次是按文件中顺序的正则匹配 ~或~*
然后匹配不带任何修饰符的一般前缀匹配
最后是交给 / 通用匹配

location 示例说明

详情
1)location = / {}

=为精确匹配 / ,主机名后面不能带任何字符串,比如访问 / 和 /data,则 / 匹配,/data 不匹配
再比如 location = /abc,则只匹配/abc ,/abc/或 /abcd 不匹配。若 location /abc,则即匹配/abc 、/abcd/ 同时也匹配 /abc/。
2)location / {}

因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求 比如访问 / 和 /data, 则 / 匹配, /data 也匹配,
但后面前缀路径会和最长字符串优先匹配(最长匹配)
3)location /documents/ {}

匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索其它 location
只有其它 location 后面的前缀路径没有匹配到时,才会采用这一条
4)location /documents/abc {}

匹配任何以 /documents/abc 开头的地址,匹配符合以后,还要继续往下搜索其它 location
只有其它 location 后面的前缀路径没有匹配到时,才会采用这一条
5)location ^~ /images/ {}

匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条
6)location ~\* \.(gif|jpg|jpeg)$ {}

匹配所有以 gif、jpg 或 jpeg 结尾的请求
然而,所有请求 /images/ 下的图片会被 location ^~ /images/ 处理,因为 ^~ 的优先级更高,所以到达不了这一条正则
7)location /images/abc {}

最长字符匹配到 /images/abc,优先级最低,继续往下搜索其它 location,会发现 ^~ 和 ~ 存在
8)location ~ /images/abc {}

匹配以/images/abc 开头的,优先级次之,只有去掉 location ^~ /images/ 才会采用这一条
9)location /images/abc/1.html {}

匹配/images/abc/1.html 文件,如果和正则 location ~ /images/abc/1.html 相比,正则优先级更高

优先级总结

(location = 完整路径) > (location ^~ 路径) > (location ,* 正则顺序) > (location 部分前缀路径) > (location /)

首先看 优先级:精确= > 前缀^~ > 正则,* > 一般 > 通用/

注意

在没有精确匹配的时候,先看所有前缀的长度,取最长匹配的 location;

如果最长的前缀匹配是带有~~的,则匹配,直接使用^~的 location 匹配用户的访问路径并跳转页面;如果最长的前缀匹配是不带^~的,则会继续看其它的正则匹配

前缀匹配看长度,最长的优先匹配;正则匹配看上下顺序,根据配置文件的配置由上往下依次匹配,匹配到即停止

3.rewrite

rewrite 功能

  • rewrite 功能就是,使用 nginx 提供的全局变量或自己设置的变量,结合正则表达式和标记位实现 URL 重写以及重定向。
  • 比如:更换域名后需要保持旧的域名能跳转到新的域名上、某网页发生改变需要跳转到新的页面、网站防盗链等等需求
  • rewrite 只能放在 server{},location{},if{}中,并且默认只能对域名后边的除去传递的参数外的字符串起作用,
  • 例如 http://www.kgc.com/abc/bbs/index.php?a=1&b=2 只对/abc/bbs/index.php 重写。

rewrite 跳转实现

  • Nginx:通过 ngx_http_rewrite_module 模块支持 URL 重写、支持 if 条件判断,但不支持 else
  • 跳转:从一个 location 跳转到另一个 location,循环最多可以执行 10 次,超过后 nginx 将返回 500 错误
  • PCRE 支持:perl 兼容正则表达式的语法规则匹配
  • 重写模块 set 指令:创建新的变量并设其值

rewrite 执行顺序

(1) 执行 server 块里面的 rewrite 指令。
(2) 执行 location 匹配。
(3) 执行选定的 location 中的 rewrite 指令

语法格式

rewrite <regex> <replacement> [flag];
regex :表示正则匹配规则。
replacement :表示跳转后的内容。
flag :表示 rewrite 支持的 flag 标记。

flag标记说明
last :本条规则匹配完成后,不终止重写后的url匹配,一般用在 server 和 if 中。
break :本条规则匹配完成即终止,终止重写后的url匹配,一般使用在 location 中。
redirect :返回302临时重定向,浏览器地址会显示跳转后的URL地址。
permanent :返回301永久重定向,浏览器地址栏会显示跳转后的URL地址。

rewrite 示例

实例 1:

将请求http://bbs.yy.com/abc/index.html的访问跳到http://www.yy.com/bbs/abc/index.html保证原域名后面的url路径不变

详情
location /abc {
rewrite (.+) http://www.yy.com/bbs$1 permanent;
}                                              #这里的$1为位置变量,代表/abc

location / {
root html;
index index.html index.htm;
}

systemctl restart nginx                        #重启nginx服务

实例 2:

将请求http://www.yy.com/bbs/index.html跳转到http://www.benet.com/bbs/index.html,保证原域名后面的url路径不变

详情
location  / {
       if ($host = 'www.yy.com'){
       rewrite ^/(.*)$ http://www.benet.com/$1 permanent;
}
       root html;
       index index.html index.htm;
}

systemctl restart nginx                        #重启nginx服务

实例 3:

将请求http://www.yy.com/abc/123.html 跳转到首页http://www.yy.com

详情
if ($request_uri ~ ^/abc/123.html$) {
rewrite (.+) http://www.yy.com permanent;
}

$request_uri:包含请求参数的原始URI,不包含主机名
$uri:这个变量指当前的请求URI,不包括任何参数
$document_uri:与$uri相同,这个变量指当前的请求URI,不包括任何传递参数

systemctl restart nginx                   #重启nginx服务

实例 4:

将对http://www.yy.com网站的所有请求跳转到自定义的维护页面

详情
set $rewrite true;
if ($remote_addr = "192.168.88.13") {
set $rewrite false;
}

if ($rewrite = true) {
rewrite (.+) /weihu.html;
}

location = /weihu.html {
root html;
}

#只有 IP 为 192.168.88.13 能正常访问,其他地址都是维护页面

systemctl restart nginx #重启服务

其他

Nginx 反向代理中 proxy_set_header 参数说明open in new window

proxy_protocolopen in new window

Nginx 变更 HTTP2 配置过程记录open in new window

Nginx 配置中的 log_formatopen in new window

后端实践:Nginx 日志配置(超详细)open in new window

Nginx 的 upstream 反向代理、负载均衡(upstream/stream)详解open in new window

Nginx 基于 stream_proxy、stream_upstream 模块实现四层反向代理负载均衡open in new window

nginx--基于 crond 定时服务+shell 脚本实现 nginx 日志自动清理及备份open in new window

demo

上次编辑于: