Nginx的配置及使用

Nginx

Nginx (engine x) 是一个高性能的HTTP和反向代理服务,也是一个IMAP/POP3/SMTP服务。
Nginx 可以在大多数 UnixLinux OS 上编译运行,并有 Windows 移植版。 Nginx 的1.4.0稳定版已经于2013年4月24日发布,一般情况下,对于新建站点,建议使用最新稳定版作为生产版本,已有站点的升级急迫性不高。
Nginx相较于Apache、lighttpd具有占有内存少,稳定性高等优势,并且依靠并发能力强,丰富的模块库以及友好灵活的配置而闻名。 在Linux操作系统下,nginx使用epoll事件模型,得益于此,nginx在Linux操作系统下效率相当高。同时Nginx在OpenBSD或 FreeBSD操作系统上采用类似于epoll的高效事件模型kqueue。

Nginx的优势

1、作为Web服务器,Nginx处理静态文件、索引文件,自动索引的效率非常高
2、作为代理服务器,Nginx可以实现无缓存的反向代理加速,提高网站运行速度
3、作为负载均衡服务器,Nginx既可以在内部直接支持Rails和PHP,也可以支持HTTP代理服务器对外进行服务,同时还支持简单的容错和利用算法进行负载均衡
4、在性能方面,Nginx是专门为性能优化而开发的,实现上非常注重效率。它采用内核Poll模型,可以支持更多的并发连接,最大可以支持对5万个并发连接数的响应,而且只占用很低的内存资源
5、在稳定性方面,Nginx采取了分阶段资源分配技术,使得CPU与内存的占用率非常低。Nginx官方表示,Nginx保持1万个没有活动的连接,而这些连接只占用2.5MB内存,因此,类似DOS这样的攻击对Nginx来说基本上是没有任何作用的
6、在高可用性方面,Nginx支持热部署,启动速度特别迅速,因此可以在不间断服务的情况下,对软件版本或者配置进行升级,即使运行数月也无需重新启动,几乎可以做到7x24小时不间断地运行。

Nginx的安装、配置与维护

安装

nginx的获取

RPM包获取:http://nginx.org/packages/
源码包获取:http://nginx.org/download/

nginx的rpm包安装

# 下载nginx的rpm包
[root@localhost ~]# wget http://nginx.org/packages/centos/7/x86_64/RPMS/nginx-1.14.2-1.el7_4.ngx.x86_64.rpm
--2019-04-16 14:34:56--  http://nginx.org/packages/centos/7/x86_64/RPMS/nginx-1.14.2-1.el7_4.ngx.x86_64.rpm
Resolving nginx.org (nginx.org)... 95.211.80.227, 62.210.92.35, 2001:1af8:4060:a004:21::e3
Connecting to nginx.org (nginx.org)|95.211.80.227|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 771856 (754K) [application/x-redhat-package-manager]
Saving to: ‘nginx-1.14.2-1.el7_4.ngx.x86_64.rpm’

100%[======================================>] 771,856     34.1KB/s   in 21s

2019-04-16 14:35:18 (36.4 KB/s) - ‘nginx-1.14.2-1.el7_4.ngx.x86_64.rpm’ saved [771856/771856]

[root@localhost ~]# ls
anaconda-ks.cfg  initial-setup-ks.cfg  nginx-1.14.2-1.el7_4.ngx.x86_64.rpm
# 安装nginx
[root@localhost ~]# yum localinstall -y nginx-1.14.2-1.el7_4.ngx.x86_64.rpm

nginx源码安装


# 添加nginx用户和用户组
[root@localhost ~]# groupadd -r -g 108 nginx
[root@localhost ~]# useradd -r -u 108 -g 108 nginx
[root@localhost ~]# id nginx
uid=108(nginx) gid=108(nginx) groups=108(nginx)
# 解压
[root@localhost ~]# tar xvf nginx-1.8.0.tar.gz -C /usr/local/src/
# 安装依赖包 gcc gcc-c++ make recp pcre-devel openssl openssl-devel
[root@localhost ~]# yum install -y gcc gcc-c++ make recp pcre-devel openssl openssl-devel
# 安装nginx
[root@localhost src]# cd /usr/local/src/nginx-1.8.0/
[root@localhost nginx-1.8.0]# ls
auto     CHANGES.ru  configure  html     man     src
CHANGES  conf        contrib    LICENSE  README
[root@localhost nginx-1.8.0]# ./configure --prefix=/usr/local/nginx/ --with-http_stub_status_module --with-openssl=/usr/local/openssl

### 安装参数
参数详解:
--prefix= 指向安装目录
--sbin-path 指向(执行)程序文件(nginx)
--conf-path= 指向配置文件(nginx.conf)
--error-log-path= 指向错误日志目录
--http-log-path= 指向访问日志
--pid-path= 指向pid文件(nginx.pid)
--lock-path= 指向lock文件(nginx.lock)(安装文件锁定,防止安装文件被别人利用,或自己误操作。)
--user= 指定程序运行时的非特权用户
--group= 指定程序运行时的非特权用户组
--with-http_ssl_module 启用ngx_http_ssl_module支持(使支持https请求,需已安装openssl)
--with-http_flv_module 启用ngx_http_flv_module支持(提供寻求内存使用基于时间的偏移量文件)
--with-http_sub_module 启用ngx_http_sub_module支持(允许用一些其他文本替换nginx响应中的一些文本)
--with-http_gzip_static_module 启用ngx_http_gzip_static_module支持(在线实时压缩输出数据流)
--http-client-body-temp-path= 设定http客户端请求临时文件路径
--http-proxy-temp-path= 设定http代理临时文件路径
--http-fastcgi-temp-path= 设定http fastcgi临时文件路径
--http-uwsgi-temp-path= 设定http uwsgi临时文件路径
--http-scgi-temp-path= 设定http scgi临时文件路径
--with-pcre 启用pcre库

[root@localhost nginx-1.8.0]# make && make install


# 配置全局变量方便使用和启动
[root@localhost nginx]# vi /etc/profile
export PATH=/usr/local/nginx/sbin:$PATH
[root@localhost nginx]# source /etc/profile
[root@localhost nginx]# vi /usr/lib/systemd/system/nginx.service
[Unit]				//对服务的说明
Description=nginx - high performance web server				//描述服务
After=network.target remote-fs.target nss-lookup.target				//描述服务类别

[Service]				//服务的一些具体运行参数的设置
Type=forking				//后台运行的形式
PIDFile=/usr/local/nginx/logs/nginx.pid				//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				 //服务用户的模式

# 创建一个文件夹用于保存不同网站的配置文件
[root@localhost nginx]# mkdir /usr/local/nginx/conf.d

如果在重启或启动nginx服务时无法启动,报错为80端口被占用

sudo fuser -k 80/tcp #关闭占用80端口的程序

nginx配置文件详解

(1)nginx 的安装目录文件
[root@localhost conf.d]# tree /etc/nginx/
/etc/nginx/
├── conf.d
│ ├── default.conf 主配置文件
│ └── default.conf.bak
├── fastcgi_params
├── koi-utf
├── koi-win
├── mime.types
├── modules -> …/…/usr/lib64/nginx/modules
├── nginx.conf
├── scgi_params
├── uwsgi_params
└── win-utf

(2)主配置文件下详解
Nginx主配置文件nginx.conf是一个纯文本类型的文件,整个配置文件是以区块的形式组织的,每一个区块以一个大括号“{}”来表示,区块可以分为几个层次,整个配置文件中,Main区位于上层,在Main区下面可以有Events区、HTTP区等层次,在HTTP区中又包含有一个或者多个server区,每个server区中又可有一个或者多个location区。
在这里插入图片描述Nginx配置文件为nginx.conf

Nginx压缩输出配置:

Nginx使用gzip压缩技术,这种技术可以压缩文件至原来的30%甚至更小。IE、FireFox、Opera、Chrome等大多浏览器都支持解析gzip过的页面.
Gzip指令用于http{…}之间
如下

http{
…
    gzip on;
    gzip_min_length 1k;
    gzip_buffer 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;#accpet_encoding gzip
…
}

nginx虚拟机主机与多虚拟主机配置

1虚拟主机介绍

1.1 虚拟主机的概念

所谓的虚拟主机,在web服务器里就是一个独立的网络站点,这个站点对应独立的域名(也可能是IP或端口),具有独立的程序及资源目录,可以独立地对外服务供用户访问。
这个独立的站点在配置里是有一定格式的标签段标记的,对于Apache软件来说,一个虚拟主机的标签通常被包含在内,而Nginx软件则使用一个serve{}标签来表示一个虚拟主机。一个Web服务里可以有多个虚拟主机标签对,既可以同时支持多个虚拟主机站点。

1.2 虚拟主机类型

基于域名的虚拟主机:通过不同的域名区分不同的虚拟主机。企业应用最广,几乎所有对外提供服务的网站使用的都是基于域名的虚拟主机。
基于端口的虚拟主机:通过不同的端口来区分不同的虚拟主机。多用于企业内部的网站。
基于IP的虚拟主机:通过不同的IP区分同的虚拟主机,此类虚拟主机的应用场景都会在负载均衡器上进行VIP绑定,而不是在web上绑定IP来区分不同的虚拟机

2虚拟主机实战

2.1基于域名的虚拟主机配置
# 网站的数据分别存在/data/a/basic/和/data/b/basic/文件夹下,日志文件存放在/data/a/log/和/data/b/log/文件夹下,网站的配置文件存放在/usr/local/nginx/conf.d/文件夹下
[root@localhost data]# mkdir -p /data/a/basic
[root@localhost data]# mkdir -p /data/b/basic
[root@localhost data]# mkdir -p /data/a/log
[root@localhost data]# mkdir -p /data/b/log
[root@localhost data]# chown -R nginx:nginx /data/a/basic/
[root@localhost data]# chown -R nginx:nginx /data/a/log/
[root@localhost data]# chown -R nginx:nginx /data/b/log/
[root@localhost data]# chown -R nginx:nginx /data/b/basic/

# 配置防火墙
[root@localhost data]# setenforce 0
[root@localhost data]# sed -ri '/^SELINUX/c\SELINUX=disabled' /etc/selinux/config
[root@localhost data]# firewall-cmd --permanent --add-service=http
success
[root@localhost data]# firewall-cmd --permanent --add-service=https
success
[root@localhost data]# firewall-cmd --reload
success
[root@localhost data]# firewall-cmd --permanent --list-all
public
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: ssh dhcpv6-client http https
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

# 写入网站内容,方便观察
[root@localhost data]# echo 'this is a' > /data/a/basic/index.html
[root@localhost data]# echo 'this is b' > /data/b/basic/index.html

使用DNS或本地hosts文件,这里采用hosts文件实现
C:\Windows\System32\drivers\etc\hosts
192.168.130.152 www.a.com
192.168.130.152 www.b.com

新建一个配置文件存放的目录

mkdir /usr/local/nginx/conf.d/

配置nginx.conf文件,添加如下内容

# 在http板块下添加
include /usr/local/nginx/conf.d/*;

新建一个配置文件

server {
        listen       192.168.130.152:80;
        server_name  www.a.com;
        access_log /data/a/access.log combined;
        location / {
            root   /data/a/basic;
            index  index.html index.htm;
        }
}
server {
        listen       192.168.130.152:80;
        server_name  www.b.com;
        access_log /data/b/log/access.log combined;
        location / {
            root   /data/b/basic;
            index  index.html index.htm;
        }
}

浏览器访问域名如下
在这里插入图片描述
在这里插入图片描述
配置完成

2.2基于端口的虚拟主机配置

借助于之前配置的文件内容。

server {
        listen       192.168.130.152:8080;
        server_name  www.web.com;
        access_log /data/a/log/access.log combined;
        location / {
            root   /data/a/basic;
            index  index.html index.htm;
        }
}

server {
        listen       192.168.130.152:8081;
        server_name  www.web.com;
        access_log /data/b/log/access.log combined;
        location / {
            root   /data/b/basic;
            index  index.html index.htm;
        }
}


配置防火墙

[root@localhost nginx]# firewall-cmd --zone=public --add-port=8080/tcp --permanent
success
[root@localhost nginx]# firewall-cmd --zone=public --add-port=8081/tcp --permanent
success
[root@localhost nginx]# firewall-cmd --zone=public --query-port=8080/tcp --permanent
yes
[root@localhost nginx]# firewall-cmd --zone=public --query-port=8081/tcp --permanent
yes
[root@localhost nginx]# firewall-cmd --reload
success

[root@localhost nginx]# nginx -t
nginx: the configuration file /usr/local/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx//conf/nginx.conf test is successful
[root@localhost nginx]# systemctl restart nginx

hosts文件中写入
192.168.130.152 www.web.com

在这里插入图片描述
在这里插入图片描述
测试不同端口成功

2.3基于IP的虚拟主机配置

测试环境可以通过给ens33子接口添加地址。
(1)在服务器网卡上增加多个IP
配置基于IP的虚拟主机,就需要让每一个虚拟主机有不同的IP地址,因此以增加辅助IP的形式临时在eth0网卡上增加2个不同的IP。

[root@localhost nginx]# ip addr add 10.0.0.1/24 dev ens33
[root@localhost nginx]# ip addr add 10.0.0.2/24 dev ens33
[root@localhost nginx]# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:48:e1:bc brd ff:ff:ff:ff:ff:ff
    inet 192.168.130.152/24 brd 192.168.130.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet 10.0.0.1/24 scope global ens33
       valid_lft forever preferred_lft forever
    inet 10.0.0.2/24 scope global secondary ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::27cc:6f91:bf44:951d/64 scope link
       valid_lft forever preferred_lft forever
    inet6 fe80::b50d:c7e1:e630:6e81/64 scope link tentative dadfailed
       valid_lft forever preferred_lft forever


[root@localhost nginx]# ping 10.0.0.1
PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.
64 bytes from 10.0.0.1: icmp_seq=1 ttl=64 time=0.037 ms
64 bytes from 10.0.0.1: icmp_seq=2 ttl=64 time=0.080 ms
^C
--- 10.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.037/0.058/0.080/0.022 ms
[root@localhost nginx]# ping 10.0.0.2
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.046 ms
64 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.037 ms
^C
--- 10.0.0.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.037/0.041/0.046/0.007 ms

编辑配置文件nginx.conf

server {
        listen       10.0.0.1:80;
        server_name  www.ipa.com;
        access_log /data/ipa/log/access.log combined;
        location / {
            root   /data/ipa/basic;
            index  index.html index.htm;
        }
}

server {
        listen       10.0.0.2:80;
        server_name  www.ipb.com;
        access_log /data/ipb/log/access.log combined;
        location / {
            root   /data/ipb/basic;
            index  index.html index.htm;
        }
}

测试

# 在hosts文件中添加
[root@localhost nginx]# echo '10.0.0.1 www.ipa.com' >> /etc/hosts
[root@localhost nginx]# echo '10.0.0.2 www.ipb.com' >> /etc/hosts
# 使用elinks测试,显示网页无误
[root@localhost nginx]# elinks --dump www.ipa.com
   this is ipa test 10.0.0.1
[root@localhost nginx]# elinks --dump www.ipb.com
   this is ipb test 10.0.0.2

location规则与地址重写

location规则介绍

location是nginx的精华,nginx就是通过拦截到的请求去对配置好的location块(location block)进行请求代理的。

location是用来具体配置代理路径的,具体格式如下:

location [=|~|~*|^~|@] /uri/ { … }

被代理的url去对location后边的字符串(或正则)进行匹配,根据一定的规则选择走哪个location,以下是匹配规则。
语法规则: location [=|~|~*|^~] /uri/ { … }
= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~ 开头表示区分大小写的正则匹配
~* 开头表示不区分大小写的正则匹配
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配的正则
/ 通用匹配,任何请求都会匹配到
-f 和!-f 用来判断是否存在文件
-d 和!-d 用来判断是否存在目录
-e 和!-e 用来判断是否存在文件或目录
-x 和!-x 用来判断文件是否可执行

Localtion的匹配规则,首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。
例子,有如下匹配规则:
location = / {
#规则A
}
location = /login {
#规则B
}
location ^~ /static/ {
#规则C
}
location ~ .(gif|jpg|png|js|css)$ {
#规则D
}
location ~* .png$ {
#规则E
}
location !~ .xhtml$ {
#规则F
}
location !~* .xhtml$ {
#规则G
}
location / {
#规则H
}
那么产生的效果如下:
访问根目录/, 比如http://localhost/ 将匹配规则A
访问 http://localhost/login 将匹配规则B,http://localhost/register 则匹配规则H
访问 http://localhost/static/a.html 将匹配规则C
访问 http://localhost/a.gif, http://localhost/b.jpg 将匹配规则D和规则E,但是规则D顺序优先,规则E不起作用,而 http://localhost/static/c.png 则优先匹配到 规则C
访问 http://localhost/a.PNG 则匹配规则E, 而不会匹配规则D,因为规则E不区分大小写。
访问http://localhost/a.xhtml 不会匹配规则F和规则G,http://localhost/a.XHT
ML不会匹配规则G,因为不区分大小写。规则F,规则G属于排除法,符合匹配规则但是不会匹配到,所以想想看实际应用中哪里会用到。
访问 http://localhost/category/id/1111 则最终匹配到规则H,因为以上规则都不匹配,这个时候应该是nginx转发请求给后端应用服务器,比如FastCGI(php),tomcat(jsp),nginx作为方向代理服务器存在。
所以实际使用中,通常至少有三个匹配规则定义,如下:
#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。
#这里是直接转发给后端应用服务器了,也可以是一个静态首页
#第一个必选规则
location = / {
proxy_pass http://tomcat:8080/index
}

#第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
#有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
root /webroot/static/;
}
location ~* .(gif|jpg|jpeg|png|css|js|ico)$ {
root /webroot/res/;
}

#第三个规则就是通用规则,用来转发动态请求到后端应用服务器
#非静态文件请求就默认是动态请求,自己根据实际把握
#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了
location / {
proxy_pass http://tomcat:8080/
}

地址重写介绍

Rewrite对称URL Rewrite,即URL重写,就是把传入Web的请求重定向到其他URL的过程。

1.URL Rewrite最常见的应用是URL伪静态化,是将动态页面显示为静态页面方式的一种技术。比如http://www.123.com/news/index.php?id=123 使用URLRewrite 转换后可以显示为 http://www.123.com/news/123.html对于追求完美主义的网站设计师,就算是网页的地址也希望看起来尽量简洁明快。理论上,搜索引擎更喜欢静态页面形式的网页,搜索引擎对静态页面的评分一般要高于动态页面。所以,UrlRewrite可以让我们网站的网页更容易被搜索引擎所收录。

2.从安全角度上讲,如果在URL中暴露太多的参数,无疑会造成一定量的信息泄漏,可能会被一些黑客利用,对你的系统造成一定的破坏,所以静态化的URL地址可以给我们带来更高的安全性。

3.实现网站地址跳转,例如用户访问360buy.com将其跳转到jd.com。例如当用户访问tianyun.com的80端口时,将其跳转到443端口。

和apache等web服务软件一样,rewrite的组要功能是实现URL地址的重定向。Nginx的rewrite功能需要PCRE软件的支持,即通过perl兼容正则表达式语句进行规则匹配的。默认参数编译nginx就会支持rewrite的模块,但是也必须要PCRE的支持。
rewrite是实现URL重写的关键指令,根据regex(正则表达式)部分内容,重定向到replacement,结尾是flag标记。

rewrite语法

rewrite语法格式及参数语法说明如下:

rewrite<regex><replacement>[flag];
关键字正则替代内容flag标记

关键字:其中关键字rewrite不能改变
正则:perl兼容正则表达式语句进行规则匹配
替代内容:将正则匹配的内容替换成replacement
flag标记:rewrite支持的flag标记

flag标记说明:
last #本条规则匹配完成后,继续向下匹配新的location URI规则
break #本条规则匹配完成即终止,不再匹配后面的任何规则
redirect #返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent #返回301永久重定向,浏览器地址栏会显示跳转后的URL地址

rewrite 企业应用场景

Nginx的rewrite功能在企业里应用非常广泛:
可以调整用户浏览的URL,看起来更规范,合乎开发及产品人员的需求。
为了让搜索引擎搜录网站内容及用户体验更好,企业会将动态URL地址伪装成静态地址提供服务。
网址换新域名后,让旧的访问跳转到新的域名上。例如,访问京东的360buy.com会跳转到jd.com
根据特殊变量、目录、客户端的信息进行URL调整等

location地址重写实例

实例1:如果访问不存在的任意网页都重定向到错误页面
server {
        listen       192.168.130.152:80;
        server_name  www.web.com;
        access_log /data/web/log/access.log combined;
        location / {
            root   /data/web/basic;
            index  index.html index.htm;
            if (!-f $request_filename) {
                rewrite /.* /err.html permanent;
            }
        }
}

测试
如果输入一个存在的页面index.html,则成功跳转
在这里插入图片描述
这里输入一个不存在的页面如b.html,自动跳转到err.html页面
在这里插入图片描述

实例2:为某个目录定义别名,将其转发到另外一个页面
# 创建测试的文件夹
[root@www ~]# mkdir /data/web/basic/to
[root@www ~]# cd /data/web/basic
[root@www basic]# echo 'test to' > to/index.html
[root@www basic]# cat to/index.html
test to

# 编辑配置文件
[root@www conf.d]# vi web.conf
server {
        listen       192.168.130.152:80;
        server_name  www.web.com;
        access_log /data/web/log/access.log combined;
        location / {
            root   /data/web/basic;
            index  index.html index.htm;
            rewrite ^/for/(.*) /to/$1 last ;
        }
}

测试
在这里插入图片描述

实例3:实现域名跳转

创建一个新的配置文件web1.conf,使其跳转指定到web

[root@www conf.d]# vi web1.conf
server {
        listen       80;
        server_name  www.web1.com;
        rewrite ^/.* http://www.web.com/$1 last;
        location / {
            root   html;
            index  index.html ;
        }
}

在hosts文件中添加
192.168.130.152 www.web1.com

测试

[root@www conf.d]# cat /data/web/basic/index.html
this is web html test

在这里插入图片描述

nginx 常见模块原理实现

basic认证模块原理实践
BASIC认证概述

在HTTP协议进行通信的过程中,HTTP协议定义了基本认证过程以允许HTTP服务器对WEB浏览器进行用户身份证的方法,当一个客户端向HTTP服务 器进行数据请求时,如果客户端未被认证,则HTTP服务器将通过基本认证过程对客户端的用户名及密码进行验证,以决定用户是否合法。客户端在接收到HTTP服务器的身份认证要求后,会提示用户输入用户名及密码,然后将用户名及密码以BASE64加密,加密后的密文将附加于请求信息中, 如当用户名为anliu,密码为:123456时,客户端将用户名和密码用“:”合并,并将合并后的字符串用BASE64加密为密文,并于每次请求数据 时,将密文附加于请求头(Request Header)中。HTTP服务器在每次收到请求包后,根据协议取得客户端附加的用户信息(BASE64加密的用户名和密码),解开请求包,对用户名及密码进行验证,如果用 户名及密码正确,则根据客户端请求,返回客户端所需要的数据;否则,返回错误代码或重新要求客户端提供用户名及密码。

BASIC认证的过程

1.客户端向服务器请求数据,请求的内容可能是一个网页或者是一个其它的MIME类型,此时,假设客户端尚未被验证,则客户端提供如下请求至服务器:
Get /index.html HTTP/1.0
Host:www.google.com
2.服务器向客户端发送验证请求代码401,服务器返回的数据大抵如下:
HTTP/1.0 401 Unauthorised
Server: SokEvo/1.0
WWW-Authenticate: Basic realm=“google.com
Content-Type: text/html
Content-Length: xxx
3.当符合http1.0或1.1规范的客户端(如IE,FIREFOX)收到401返回值时,将自动弹出一个登录窗口,要求用户输入用户名和密码。
4.用户输入用户名和密码后,将用户名及密码以BASE64加密方式加密,并将密文放入前一条请求信息中,则客户端发送的第一条请求信息则变成如下内容:
Get /index.html HTTP/1.0
Host:www.google.com
Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxx
注:xxxx…表示加密后的用户名及密码。
5. 服务器收到上述请求信息后,将Authorization字段后的用户信息取出、解密,将解密后的用户名及密码与用户数据库进行比较验证,如用户名及密码正确,服务器则根据请求,将所请求资源发送给客户端:

BASIC认证的缺点

HTTP基本认证的目标是提供简单的用户验证功能,其认证过程简单明了,适合于对安全性要求不高的系统或设备中,如大家所用路由器的配置页面的认证,几乎 都采取了这种方式。其缺点是没有灵活可靠的认证策略,如无法提供域(domain或realm)认证功能,另外,BASE64的加密强度非常低,可以说仅 能防止sohu的搜索把它搜到了。当然,HTTP基本认证系统也可以与SSL或者Kerberos结合,实现安全性能较高(相对)的认证系统

basic的nginx实现

nginx用户认证配置( Basic HTTP authentication)
nginx_http_auth_basic_module模块实现让访问着,只有输入正确的用户密码才允许访问web内容。web上的一些内容不想被其他人知道,但是又想让部分人看到。nginx的http auth模块以及Apache http auth都是很好的解决方案。
默认情况下nginx已经安装了ngx_http_auth_basic_module模块,如果不需要这个模块,可以加上 --without-http_auth_basic_module 。
nginx basic auth指令
语法: auth_basic string | off;
默认值: auth_basic off;
配置段: http, server, location, limit_except
默认表示不开启认证,后面如果跟上字符,这些字符会在弹窗中显示。
语法: auth_basic_user_file file;
默认值: —
配置段: http, server, location, limit_except
用户密码文件,文件内容类似如下
ttlsauser1:password1
ttlsauser2:password2:comment

修改配置文件

[root@www conf.d]# vi web.test.conf
server {
        listen       80;
        server_name  www.web.test.com;
        access_log /data/web/www.web.com;
        index index.html index.php;
        location / {
                auth_basic "nginx basic http test for web.com";
                auth_basic_user_file conf/htpasswd;
                autoindex on;
        }
}



[root@www conf.d]# yum install -y httpd
[root@www conf.d]# which htpasswd
/usr/bin/htpasswd
[root@www conf.d]# printf "test:$(openssl passwd -crypt 123456)\n" > /usr/local/nginx/conf/htpasswd
[root@www conf.d]# chmod 400 /usr/local/nginx/conf/htpasswd
[root@www conf.d]# chown nginx /usr/local/nginx/conf/htpasswd
[root@www conf.d]# cat /usr/local/nginx/conf/htpasswd
test:HZ4o973aX3/V6


测试
输入用户名密码
在这里插入图片描述
在这里插入图片描述

with-http_stub_status_module 状态模块实践
Nginx status 配置

(1)生成状态配置,并增加状态配置参数
[root@www nginx]# vi /usr/local/nginx/conf/status.conf
server{
listen 80;
server_name www.status.com;
location / {
stub_status on;
access_log off;
}
}

(2)用include语句导入到主配置文件
[root@www nginx]# NUM=$(expr $(cat -n conf/nginx.conf | grep ‘http {’ |awk ‘{print $1}’) + 1);echo “sed -i ${NUM}i’\ \ \ \ include status.conf;’ conf/nginx.conf”|bash
[root@www nginx]# nginx -t
[root@www nginx]# systemctl restart nginx

测试
在这里插入图片描述
Nginxs tatus结果含义:
Active connections: 3
表示Nginx正在处理的活动连接数3个。
server accepts handled requests
8 8 67
第一个 server 表示Nginx启动到现在共处理了 8 个连接
第二个 accepts 表示Nginx启动到现在共成功创建 8 次握手
第三个 handled requests 表示总共处理了 67 次请求
请求丢失数 = 握手数 - 连接数 ,可以看出目前为止没有丢失请求

ngx_http_access_module 限制访问模块
access配置实例
location  / {
        deny 192.168.1.1;
        allow 192.168.1.0/24;
        deny all;
}

解释:
1.禁止192.168.1.1这个ip地址访问
2.允许192.168.1.0/24这个地址段的ip访问,但是由于192.168.1.1首先匹配deny,因此192.168.1.1是无法访问的
3.当ip地址不匹配1,2两条规则时,将禁止所有的ip地址访问

gx_http_gzip_module模块

这个模块支持在线实时压缩输出数据流

使用范例

: gzip on;
: gzip_min_length 1000;
: gzip_proxied expired no-cache no-store private auth;
: gzip_types text/plain application/xml;
内置变量 $gzip_ratio 可以获取到gzip的压缩比率

配置说明

Nginx开启Gzip的配置如下:

$gzip_ratio计算请求的压缩率,$body_bytes_sent请求体大小
log_format main '$remote_addr - $remote_user [$time_local] “$host” - “$request” ’
‘$gzip_ratio - $body_bytes_sent - $request_time’;

access_log logs/access.log main;

开启gzip
gzip on;

启用gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k;

gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
gzip_comp_level 1;

进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
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/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml;

是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;

禁用IE 6 gzip
gzip_disable “MSIE [1-6].”;

设置压缩所需要的缓冲区大小
gzip_buffers 32 4k;

设置gzip压缩针对的HTTP协议版本
gzip_http_version 1.0;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值