Nginx的常见用法

一、基本配置

配置文件格式

CoreModule 核心模块
EventModule 事件驱动模块
HttpCoreModule http内核模块
CoreModule下可以有EventModule、HttpCoreModule
HttpCoreModule下可以有多个Server,Server用于配置站点
Server下又可以有多个location,location用于定义网站访问路径

  • 查看/etc/nginx/nginx.conf

    user  nginx; #nginx进程所使用的用户
    worker_processes  1; #nginx运行的worker进程数量
    error_log  /var/log/nginx/error.log warn; #nginx错误日志存放路径
    pid        /var/run/nginx.pid; #nginx服务运行后产生的pid进程号
    keepalive_timeout 0; #保持连接的超时时间(调整长连接或短连接)
    events {
        worker_connections  1024; #每个worker进程支持的最大连接数
    }
    
    http{
    	server { #Server用于配置站点,每个Server{}代表一个网站(虚拟主机)
    		listen 80; #监听80端口
    		server_name localhost; #提供服务的域名或主机名
    		access_log  /var/log/nginx/access.log; #访问日志
    		location / { #控制网站访问路径
    			root /usr/share/nginx/html; #存放网站代码的路径
    			index index.php index.html; #服务器返回的默认页面文件
    		}
    		location /downlode {
    			...
    		}
    		error_page 500 502 504 /50x.html #错误代码以及对应的location
    		
    	}
    	server {
    		...
    	}
    	include /etc/nginx/conf.d/*.conf; #内嵌的其他文件
    	include /etc/nginx/mime.types; #mime.types文件涵盖了nginx所支持的资源类型
    }
    

日志配置

日志包括:error.log,access.log

access.log

  • 参数
    $remote_addr:远程IP;
    $remote_user:远程用户;
    $stime_local:时间;
    $request:用来记录请求的url与http协议;
    $status:用来记录请求状态;成功是200;
    $body_bytes_sent:记录发送给客户端文件主体内容大小;
    $http_referer:用来记录从那个页面链接访问过来的;
    $http_user_agent:记录客户浏览器的相关信息;
    $http_x_forwarded_for:访问用户的真实 IP 地址;

  • 例子
    默认的格式

    log_format main '$remote_addr - $remote_user [time_local] $request' '"$status" $body_bytes_sent "$http_referer"' '"$http_user_agent" "$http_x_forwarded_for"'
    

    把源客户端的真实IP记录下来(否则只是记录代理的地址)

    log_format main1 '$proxy_add_x_forwarded_for - $remote_user [$time_local]' '"$request" $status $body_bytes_sent' '"$http_referer" "$http_user_agent"';
    

    使用main1格式来配置日志

    access_log  /var/log/nginx/access.log  main1;
    

error.log

  • 参数
    错误日志级别:
    [debug | info | notice | warn | error | crit | alert | emerg]

  • 例子

    error_log  /var/log/nginx/error.log warn; #warn,error,crit正式环境常用
    

Location

  • 规则

    匹配符匹配规则优先级
    =精确匹配1
    ^~以某个字符串开头2
    ~区分大小写的正则匹配3
    ~*不区分大小写的正则匹配4
    !~区分大小写不匹配的正则5
    !~*不区分大小写不匹配的正则6
    /通用匹配7
  • 例子

    location / {...} #通用匹配
    location ~ \.jsp$ { #区分大小写,匹配以.jsp结尾的都走这个路径
    	proxy_pass http://127.0.0.1:8080;
    } 
    location ~* .*\.(jpg|gif|png|js|css)$ { #不区分大小写,用户访问jpg|gif|png|js|css 就走这个路径
    	return 302 http://data.maishihui.com
    }
    

二、静态服务

静态网页

  • 进入配置目录
    cd /etc/nginx/conf.d

  • 新建配置文件
    cp default.conf static.conf
    rename default.conf default.off default.conf

  • 编辑配置文件
    static.conf

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
        location /mybd {
            root /usr/share/nginx/my;
            index mybd.html;
        }   
    }
    
  • 获取静态资源

    cd /usr/share/nginx/my/mybd
    wget www.baidu.com
    mv index.html mybd.html
    
  • 启动nginx并验证

    nginx -t
    systemctl start nginx
    

    在这里插入图片描述

    目录索引

  • 需要模块ngx_http_autoindex_module

    autoindex on | off:是否开启目录浏览下载
    autoindex_exact_size on | off :是否显示文件的准确大小(单位bytes)
    autoindex_localtime on | off :显示文件时间为服务器时间(on)或GMT时间(off)
    charset utf-8,gbk:解决中文目录乱码问题

  • 修改配置文件

    /etc/nginx/conf.d/static.conf增加如下内容:

    location /down {
            root /usr/share/nginx/my;
            autoindex on;
            charset utf-8;
    }
    
  • 添加资源到如下目录:/usr/share/nginx/my/down

  • 重启nginx,测试
    在这里插入图片描述

三、代理服务

反向代理

  • 环境
    Nginx 代理服务器:192.168.142.101
    Nginx Web服务器:192.168.142.102

  • 配置代理服务器

    server {
       ......
        location /lb {
            proxy_pass http://192.168.142.102:80;
            include proxy_params;
        }
    }
    

    新建proxy_params文件(位于nginx安装的根路径下):

    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
    
    proxy_connect_timeout 30s;
    proxy_read_timeout 60s;
    proxy_send_timeout 60s;
    
    proxy_buffering on;
    proxy_buffer_size 62k;
    proxy_buffers 16 128k;
    
  • 代理服务器-配置同一IP端口多域名(多站点)的情况

    proxy_set_header Host $http_host 原用户请求的主机名
    proxy_set_header X-Real-IP $remote_addr客户端IP
    proxy_set_header X-Forward-For $proxy_add_x_forwarded_for客户端真实地址

  • 代理服务器-超时时间
    proxy_connect_timeout 60s:nginx代理与后端服务器的连接超时时间
    proxy_read_timeout 60s:nginx代理等待后端服务器的响应超时时间
    proxy_send_timeout 60s:后端服务器数据回传给nginx代理超时时间

  • 代理服务器-代理缓冲区
    即把后端返回的数据先放到该缓冲区,再返回给客户端,边收边传
    proxy_buffering on; 开启缓冲区
    proxy_buffer_size 8k; 缓冲区大小。逻辑概念,响应头超过这个大小就会报错
    proxy_buffers 16 8k;缓冲区存放的文件数量和每个文件的大小,物理概念

  • 配置Web服务器
    我这里配置文件是分开的,也可以一起
    nginx.conf

    ...
    http {
    	...
    	include /etc/nginx/conf/conf.d/*.conf;
    }
    ...
    

    /etc/nginx/conf/conf.d/lb.conf

    server {
        listen       80;
        server_name  192.168.142.102;
        location /lb {
            root   /etc/nginx/web;
            index  index.html;
        }
    }
    
  • 获取网页

    cd /etc/nginx/web/lb
    echo welcome to web01 > index.html
    
  • 启动代理服务器和Web服务器,浏览器验证
    在这里插入图片描述

负载均衡

  • 环境
    Nginx 代理服务器:192.168.142.101
    Nginx Web服务器1:192.168.142.102
    Nginx Web服务器2:192.168.142.103

  • 配置代理服务器

    upstream backend{
            server 192.168.142.102:80;
            server 192.168.142.103:80;
            #server 192.168.142.103:80 weight=2;
            #server 192.168.142.104:80 backup;
    }
    server{
    	...
    	location /lb {
            proxy_pass http://backend;
            include proxy_params;
    	}
    }
    
  • 代理服务器-后端服务器在负载调度中的状态
    down:当前的server暂时不参与负载均衡
    backup:预留的备份服务器
    max_fails:允许请求失败的次数
    fail_timeout:经过max_fails失败后,服务暂停时间
    max_conn:限制最大的接收连接数

  • 负载均匀算法
    round robin(默认):轮询,依次将请求分配到各个后台服务器中
    weight:加权轮询,根据权重来分发请求到不同的机器中
    ip_hash:根据请求者ip的hash值将请求发送到后台服务器中,可以保证来自同一ip的请求被打到固定的机器上
    url_hash:根据请求者url的hash值将请求发送到后台服务器中
    least_conn:最少连接数,哪个机器连接数少就分发
    fair:根据后台响应时间来分发请求,响应时间短的分发的请求多

  • 配置Web服务器1

    echo welcome to web01 > index.html
    
    server {
        listen       80;
        server_name  192.168.142.102;
        location /lb {
            root   /etc/nginx/web;
            index  index.html;
        }
    }
    
  • 配置Web服务器2

    echo welcome to web02 > index.html
    
    server {
    	    listen       80;
    	    server_name  192.168.142.103;
    	    location /lb {
    	        root   /etc/nginx/web;
    	        index  index.html;
    	    }
    	}
    
  • 启动三台nginx服务,浏览器验证

Rewrite(即url重写)

语法:rewrite regex replacement[flag]

Rewrite配置中,常引用的变量:
如:http://127.0.0.1:80/store/data/1.jsp
$host:127.0.0.1
$server_port:80
$request_uri:/store/data/1.jsp
$document_root:/var/www/html
$request_filename:/var/www/html/store/data/1.jsp

匹配优先级:
server块rewrite > location匹配 > location块rewrite

关于flag
没有flag:跳转时,浏览器所显示的同一站点的地址不会变
redirect:返回302临时重定向,跳转时浏览器地址会变更为重定向的地址
permanent:返回301永久重定向,跳转时浏览器地址会变更为重定向的地址
last:本条规则匹配完成后,继续匹配后面的规则
break:本条规则匹配完成后,不再匹配后面的规则

  • 开启rewrite日志

    error_log  /var/log/nginx/error.log notice;
    http {
    	...
    	rewrite_log on;
    }
    ...
    
  • … -> https://www.baidu.com
    修改配置文件:

    location / {
    		...
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            rewrite ^/ https://www.baidu.com;
            #return 302 https://www.baidu.com;#无日志输出
    }
    

    浏览器测试,查看日志:
    在这里插入图片描述

  • 一般转换:http://192.168.142.103/aa/1.html -> http://192.168.142.103/bb/cc/1.html

    location ~* /aa/1.html {
    	rewrite .* /bb/cc/1.html;
    }
    
  • 泛域名转换:http://maishihui.store -> http://www.maishihui.store

    server {
        listen       80;
        server_name  www.maishihui.store;
        location / {
            root /etc/nginx/www;
            index index.html;
        }
        location /lb {
            root   /etc/nginx/web;
            index  index.html;
        }
    }
    server {
        listen       80;
        server_name  maishihui.store;
        location / {
            rewrite ^(.*) http://www.$server_name$1;
        }
    }
    
  • 隐藏真实路径:
    http://192.172.142.101/abc/store_33_22_11.html
    ->http://192.172.142.101/abc/store/11/22/33/store_33.html

    location / {
    	rewrite ^/abc/store_(.*)_(.*)_(.*).html$ /abc/store/$3/$2/$1/store_$1.html;
    }
    
  • 指向同一页面:
    http://192.172.142.101/2020/abc/1.html
    ->http://192.172.142.101/2018/abc/1.html

    location /2020 {
    	rewrite ^/2020/(.*)$ /2018/$1 redirect;
    }
    

支持https协议

  • 开启ssl
server{
	listen 443;
	ssl on;
	ssl_certificate ssl_key/server.crt;#证书文件存放路径
	ssl_certificate_key ssl_key/server.crt;#秘钥文件存放路径
	...
}
  • 将http转发为https
server{
	listen 80;
	server_name localhost;
	rewrite ^(.*) https://$server_name$1 redirect;
}
server{
	listen 443;
	server_name localhost;
	ssl on;
	...
}

虚拟主机

  • 修改客户端hosts文件(客户端会首先在本地查找该文件是否有对应的域名解析,没有再发送DNS服务器)
    C:\Windows\System32\drivers\etc\hosts

    192.168.142.101 www.maishihui.store blog.maishihui.store document.maishihui.store
    
  • 配置Nginx服务器,通过设置不同的域名,实现虚拟主机

    server {
        listen       80;
        server_name www.maishihui.store;
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
        .....
    }
    server {
        listen       80;
        server_name blog.maishihui.store;
        location / {
            root   /usr/share/nginx/blog;
            index  index.html index.htm;
        }
    }
    server {
        listen       80;
        server_name document.maishihui.store;
        location / {
            root   /usr/share/nginx/document;
            index  index.html index.htm;
        }
    }
    
  • 分别创建网页文件

    echo welcome to www.maishihui.store > /usr/share/nginx/html/index.html
    
    echo welcome to blog.maishihui.store > /usr/share/nginx/blog/index.html
    
    echo welcome to document.maishihui.store > /usr/share/nginx/document/index.html
    
  • 启动nginx,浏览器测试

四、安全服务

访问状态监控

  • 需要模块:ngx_http_stub_status_module

  • 修改配置文件/etc/nginx/conf.d/static.conf

    location /status {
            stub_status;
            access_log off; #关闭连接日志,该url只有系统内部人员访问,不需要记录到连接日志上去
    }
    
  • 重启nginx,测试
    在这里插入图片描述

    Active connections: 当前活动的连接数
    accepts :当前的总连接数TCP
    handled:成功的连接数TCP
    requests:总的requests请求数

IP访问控制

  • 需要模块:ngx_http_access_module

    allow 192.168.103.121 #允许该IP
    allow all #允许所有IP
    deny 192.168.103.121 #拒绝该IP
    deny all #拒绝所有IP
    从上到下匹配,满足即停止。可以先写允许的IP然后拒绝所有,或者先写拒绝的IP允许所有

  • 修改配置文件/etc/nginx/conf.d/static.conf

    location /status {
            stub_status;
            access_log off;
            allow 192.168.8.104;
            deny all;
    }
    

用户访问控制

  • 需要模块:ngx_http_auth_basic_module

    auth_basic string | off;
    auth_basic_user_file file;

  • 生成密码文件
    安装httpd-tools

    yum -y install httpd-tools
    

    生成密码文件

    htpasswd -b -c /etc/nginx/auth_conf xzt 123456
    
  • 修改配置文件/etc/nginx/conf.d/static.conf

    location /down {
            root /usr/share/nginx/my;
            autoindex on;
            charset utf-8;
            auth_basic "It's Mine";
            auth_basic_user_file /etc/nginx/auth_conf;
    }
    
  • 重启nginx,测试
    在这里插入图片描述在这里插入图片描述

访问限制

  • 需要模块:ngx_http_limit_conn_module,可防止恶意访问(攻击)

    limit_conn_mudule:连接频率限制
    limit_req_mudule:请求频率限制

连接频率限制

  • 配置语法

    limit_conn_zone key zone=name:size;#size即为该zone分配的缓存大小
    limit_conn zone number

  • 使用的变量

    binary_remote_addr 变量长度是固定4字节
    remote_addr 变量长度是7-15字节

  • 配置例子

    http{
    	limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
    	...
    	server{
    		location{
    			limit_conn conn_zone 1; #同时只能有一个IP连接
    		}
    		...
    	}
    }
    
  • 修改配置文件/etc/nginx/conf.d/static.conf

    limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
    location /mybd{
            root /usr/share/nginx/my;
            index mybd.html;
            limit_conn conn_zone 1;
     }
    
  • 重启nginx,测试(可以用多台虚拟机来测)

请求频率限制

  • 配置语法

    limit_req_zone key zone=name:size; rate=rate; #rate为每秒允许的请求频率
    limit_req zone number

  • 配置例子

    http{
    	limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
    	...
    	server{
    		location{
    			limit_req zone=req_zone burst=3 nodelay; #请求超过1r/s,剩下的会被延迟处理,超多burst的数量时,会返回503错误
    		}
    		...
    	}
    }
    
  • 修改配置文件/etc/nginx/conf.d/static.conf

    limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
    limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
    location /mybd {
            root /usr/share/nginx/my;
            index mybd.html;
            limit_conn conn_zone 1;
            limit_req zone=req_zone burst=3 nodelay;
    }
    
  • 重启Nginx测试

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值