nginx compression, https encryption realize, rewrite, common configuration Daolian

Nginx compression

ngx_http_gzip_module

#ngx_http_gzip_module 
compression method with gzip response data, save bandwidth 

# gzip compression enabled or disabled, the default closed 
gzip ON | OFF; 

# low to high compression ratio from 1 to 9, by default. 1 
gzip_comp_level Level; 

# disable IE6 gzip function 
gzip_disable " . MSIE [1-6] \ "; 

#gzip smallest compressed file, the file is smaller than the set value will not be compressed 
gzip_min_length 1k; 

# when compression is enabled, the smallest version of the protocol, the default HTTP / 1.1 
gzip_http_version 1.0 | 1.1; 

# * the number of buffer space to specify the size of the service need to Nginx server application, the default 4K 32 | 16 8k; 
gzip_buffers number the size; 

# specify only what types of resources to implement compression operations; default is gzip_types text / html, not explicit, otherwise error 
gzip_types MIME-of the type ...; 

# If you enable compression, whether in response packet header insert "Vary: the Accept-Encoding" 
gzip_vary oN | OFF;
 
when #nginx acting as a proxy server for backend server response packet, enable compression and under what conditions
OFF gzip_proxied | expired The | NO-Cache | NO-Store | Private | no_last_modified | no_etag | auth | the any ...; 

#off: not enable compression 

# expired, no-cache, no -store, private: the back-end servers response packet header Cache-Control any value, enable compression

Example:

gzip on;
gzip_comp_level 6;  
gzip_min_length 64;  
gzip_vary on;
gzip_types text/xml text/css application/javascript;

Practical exercise:

1, turn compression on Nginx server, and specify the compression type.

 2, create a f1.html large file in nginx server data / site1 directory.

[root@centos27site1]#!dd
dd if=/dev/zero  of=f1.html bs=1M count=40
40+0 records in
40+0 records out
41943040 bytes (42 MB) copied, 0.320604 s, 131 MB/s

 3, the effect of compression on the client access.

[root@centos17apps]#curl  --compress www.baidu.net/f1.html

  4, track log nginx server, view the compressed size.

https feature

Web site login page using https are encrypted transmission of encrypted data to ensure data security, HTTPS can encrypt information, so as not to acquire sensitive information by a third party, so high many banking sites or e-mail, and so will the level of security services in HTTPS, HTTPS is actually composed of two parts: HTTP + SSL / TLS, i.e. on an HTTP module added a layer of processing encrypted information. Service and client information transmitted is encrypted by TLS, so after the data transmission is encrypted data.

https 实现过程如下:
1.客户端发起HTTPS请求:
客户端访问某个web端的https地址,一般都是443端口

2.服务端的配置: 采用https协议的服务器必须要有一套证书,可以通过一些组织申请,也可以自己制作,目前国内很多网站都自 己做的,当你访问一个网站的时候提示证书不可信任就表示证书是自己做的,证书就是一个公钥和私钥匙,就像 一把锁和钥匙,正常情况下只有你的钥匙可以打开你的锁,你可以把这个送给别人让他锁住一个箱子,里面放满 了钱或秘密,别人不知道里面放了什么而且别人也打不开,只有你的钥匙是可以打开的。

3.传送证书: 服务端给客户端传递证书,其实就是公钥,里面包含了很多信息,例如证书得到颁发机构、过期时间等等。

4.客户端解析证书: 这部分工作是有客户端完成的,首先回验证公钥的有效性,比如颁发机构、过期时间等等,如果发现异常则会弹 出一个警告框提示证书可能存在问题,如果证书没有问题就生成一个随机值,然后用证书对该随机值进行加密, 就像2步骤所说把随机值锁起来,不让别人看到。

5.传送4步骤的加密数据: 就是将用证书加密后的随机值传递给服务器,目的就是为了让服务器得到这个随机值,以后客户端和服务端的通 信就可以通过这个随机值进行加密解密了。

6.服务端解密信息: 服务端用私钥解密5步骤加密后的随机值之后,得到了客户端传过来的随机值(私钥),然后把内容通过该值进行 对称加密,对称加密就是将信息和私钥通过某种算法混合在一起,这样除非你知道私钥,不然是无法获取其内部 的内容,而正好客户端和服务端都知道这个私钥,所以只要机密算法够复杂就可以保证数据的安全性。

7.传输加密后的信息: 服务端将用私钥加密后的数据传递给客户端,在客户端可以被还原出原数据内容。

8.客户端解密信息: 客户端用之前生成的私钥获解密服务端传递过来的数据,由于数据一直是加密得,因此即使第三方获取到数据也 无法知道其详细内容。

选择SSL证书品牌(CA供应商)

阿里云SSL证书申请:

https://www.aliyun.com/product/cas?spm=a2c4g.11174283.2.1.47676fd4baNCYX

支持阿里云颁发数字证书的安全CA中心包括:

1、Symantec:赛门铁克(Symantec)是全球第一大数字证书颁发机构、全球最值得信赖的SSL证书品牌,所有证书都采用业界领先的加密技术,为不同的网站和服务器提供安全解决方案

2、CFCA: 中国金融认证中心(CFCA)通过国际WebTrust认证,遵循全球统一鉴证标准,是国际CA浏览器联盟组织成员。CFCA全球信任SSL证书,由中国权威数字证书认证机构自主研发,纯国产证书。CFCA提供 7x24 小时金融级的安全保障服务,且有完善的风险承保计划。提供中文版全球信任体系电子认证业务规则(CPS),便于用户理解双方权利和义务

3、GeoTrust: GeoTrust 是全球第二大数字证书颁发机构, 也是身份认证和信任认证领域的领导者,采用各种先进的技术使任何大小的机构和公司都能安全、低成本地部署SSL数字证书和实现各种身份认证

4、GlobalSign: GMO GlobalSign是全球最早的数字证书认证机构之一,一直致力于网络安全认证及数字证书服务,是一个备受信赖的CA和SSL数字证书提供商

 选择证书类型

阿里云联合有资质的CA中心推荐以下几种数字证书配置组合方案:

免费型DV SSL: 免费型DV SSL证书是基础级SSL产品

说明 目前仅Symantec提供免费型数字证书,该证书仅支持绑定一个域名
只验证域名所有权,数小时内即可颁发
只提供通信链路加密功能
根证书一般使用CA中心认证的根证书
支持绑定一个明细子域名,且不支持通配符域名

通配符DV SSL:通配符DV SSL证书属于DV型SSL证书(Domain Validation SSL)

只验证域名所有权,数小时内即可颁发
提供高强度通信链路加密功能
支持绑定一个带有通配符的域名

 ssl 配置参数

nginx 的https 功能基于模块ngx_http_ssl_module实现,因此如果是编译安装的nginx要使用参数
ngx_http_ssl_module开启ssl功能,但是作为nginx的核心功能,yum安装的nginx默认就是开启的,编译安装的
nginx需要指定编译参数--with-http_ssl_module开启,官方文档: https://nginx.org/en/docs/http/ngx_http_ssl_
module.html,配置参数如下:

ssl on | off;
#为指定的虚拟主机配置是否启用ssl功能,此功能在1.15.0废弃,使用listen [ssl]替代。

ssl_certificate /path/to/file; #当前虚拟主机使用使用的公钥文件,一般是crt文件
ssl_certificate_key /path/to/file; #当前虚拟主机使用的私钥文件,一般是key文件
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; #支持ssl协议版本,早期为ssl现在是TSL,默认为后三个
ssl_session_cache off | none | [builtin[:size]] [shared:name:size]; #配置ssl缓存 off: 关闭缓存 none: 通知客户端支持ssl session cache,但实际不支持 builtin[:size]:使用OpenSSL内建缓存,为每worker进程私有 [shared:name:size]:在各worker之间使用一个共享的缓存,需要定义一个缓存名称和缓存空间大小,一兆可以存储4000个会话信息,多个虚拟主机可以使用相同的缓存名称。
ssl_session_timeout time; #客户端连接可以复用ssl session cache中缓存的有效时长,默认5m

示例:

server {
listen 443 ssl;
server_name www.magedu.com;
root /vhosts/ssl/htdocs;
   ssl on;
   ssl_certificate /etc/nginx/ssl/nginx.crt;
   ssl_certificate_key /etc/nginx/ssl/nginx.key;
   ssl_session_cache shared:sslcache:20m;
   ssl_session_timeout 10m;
}

自签名证书 

 1、在指定的/etc/pki/tls/certs目录下创建公私钥对。

[root@centos27certs]#cd /etc/pki/tls/certs
[root@centos27certs]#make magedu.crt
umask 77 ; \
/usr/bin/openssl genrsa -aes128 2048 > magedu.key
Generating RSA private key, 2048 bit long modulus
........................................................................+++
...............................................................+++
e is 65537 (0x10001)
Enter pass phrase:
Verifying - Enter pass phrase:
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key magedu.key -x509 -days 365 -out magedu.crt 
Enter pass phrase for magedu.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN   #国家
State or Province Name (full name) []:shanghai  #省份
Locality Name (eg, city) [Default City]:shanghai #城市
Organization Name (eg, company) [Default Company Ltd]:magedu.com #公司名称  
Organizational Unit Name (eg, section) []:opt  #部门
Common Name (eg, your name or your server's hostname) []:www.magedu.net  #通用名称
Email Address []:  #邮箱

 2、此时生成的私钥是加密状态,访问网站时用户也会需要输入密码,我们需要对其进行解密处理。

[root@centos27certs]#openssl rsa -in magedu.key -out magedu.net.key  将私钥进行解密。
[root@centos27certs]#mv magedu.crt magedu.net.crt  将证书与私钥文件格式一致。
[root@centos27certs]#ll
total 28
lrwxrwxrwx. 1 root root   49 Aug 22 15:23 ca-bundle.crt -> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
lrwxrwxrwx. 1 root root   55 Aug 22 15:23 ca-bundle.trust.crt -> /etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt
-rw-------  1 root root 1371 Dec  9 09:30 localhost.crt
-rw-------  1 root root 1766 Dec 13 11:37 magedu.key
-rw-------  1 root root 1342 Dec 13 11:37 magedu.net.crt
-rw-r--r--  1 root root 1679 Dec 13 11:38 magedu.net.key
-rwxr-xr-x. 1 root root  610 Oct 31  2018 make-dummy-cert
-rw-r--r--. 1 root root 2516 Oct 31  2018 Makefile
-rwxr-xr-x. 1 root root  829 Oct 31  2018 renew-dummy-cert

  3、新建一个存放私钥和crt文件的目录,并修改成600权限,保证安全

[root@centos27certs]#mkdir /etc/nginx/ssl
[root@centos27certs]#mv magedu.net.*  /etc/nginx/ssl/
[root@centos27certs]#chmod 600 /etc/nginx/ssl/magedu.net*

   4、修改相关的配置文件,可以将80端口和443端口同时监听在一个虚拟机中。

vim /etc/nginx/conf.d/test.conf
server  {
    listen 443 ssl;  
    listen 80;
    server_name www.magedu.net;
    root /data/ssl/;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;                                                                                                                     
    access_log  /var/log/nginx/access_json.ssl.log  access_json;
}

修改windows机器的C:\Windows\System32\drivers\etc\hosts文件,写入域名解析。

在nginx服务端创建一个网页:

echo /data/ssl/test.html > /data/ssl/index.html

验证网站访问效果:

实现自动跳转至https加密网站

vim  /etc/nginx/conf.d/test.conf
server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.net;
    root /data/ssl/;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log  /var/log/nginx/access_json.ssl.log  access_json;
    location / {                                                                                                                                 
        if ( $scheme = http ){
           return 301 https://www.magedu.net/;
        }
    }
}

 在客户端验证效果:

[root@centos17apps]#curl -Lk https://www.magedu.net   其中-k是忽略密码验证
/data/ssl/test.html

Nginx Rewrite相关功能

Nginx服务器利用ngx_http_rewrite_module 模块解析和处理rewrite请求,所以说此功能依靠 PCRE(perl
compatible regularexpression),因此编译之前要安装PCRE库,rewrite是nginx服务器的重要功能之一,用于实现
URL的重写,URL的重写是非常有用的功能,比如它可以在我们改变网站结构之后,不需要客户端修改原来的书
签,也无需其他网站修改我们的链接,就可以设置为访问,另外还可以在一定程度上提高网站的安全性。

ngx_http_rewrite_module模块指令 

将用户请求的URI基于PCRE regex所描述的模式进行检查,而后完成重定向替换

示例:

http://www.magedu.com/hn --> http://www.magedu.com/henan
http://www.magedu.com --> https://www.magedu.com/

https://nginx.org/en/docs/http/ngx_http_rewrite_module.html  

if指令  

用于条件匹配判断,并根据条件判断结果选择不同的Nginx配置,可以配置在server或location块中进行配置,
Nginx的if语法仅能使用if做单次判断,不支持使用if else或者if elif这样的多重判断,用法如下:

示例:
location /test {
index index.html;
default_type text/html;
if ( $scheme = http ){
return 301 https://www.magedu.net/;
}
if ( $scheme = https ){
echo "if ----> $scheme";
}

使用正则表达式对变量进行匹配,匹配成功时if指令认为条件为true,否则认为false,变量与表达式之间使用以下
符号链接:

=: #比较变量和字符串是否相等,相等时if指令认为该条件为true,反之为false。
!=: #比较变量和字符串是否不相等,不相等时if指令认为条件为true,反之为false。
~: #表示在匹配过程中区分大小写字符,(可以通过正则表达式匹配),满足匹配条件为真,不满足为假。
~*: #表示在匹配过程中不区分大小写字符,(可以通过正则表达式匹配),满足匹配条件为真,不满足问假。
!~:#区分大小写不匹配,不满足为真,满足为假,不满足为真。
!~*:#为不区分大小写不匹配,满足为假,不满足为真。
-f 和 ! -f:判断请求的文件是否存在和是否不存在
-d 和 ! -d: #判断请求的目录是否存在和是否不存在。
-x 和 ! -x: #判断文件是否可执行和是否不可执行。
-e 和 ! -e: #判断请求的文件或目录是否存在和是否不存在(包括文件,目录,软链接)。

注: 如果$变量的值为空字符串或是以0开头的任意字符串,则if指令认为该条件为false,其他条件为true。

set指令:

指定key并给其定义一个变量,变量可以调用Nginx内置变量赋值给key,另外set定义格式为set $key $value,及无
论是key还是value都要加$符号。

示例:

location /main {
root /data/nginx/html/pc;
index index.html;
default_type text/html;
set $name magedu;
echo $name;
set $my_port $server_port;
echo $my_port;
}

return指令

停止处理,并返回给客户端指定的响应码(包括: 204, 400, 402 — 406, 408, 410, 411, 413, 416, 500 — 504),并对 301, 302, 303, 307, 308跳转到URL

return code [text]; #返回客户端指定的状态码和文本说明
return code URL;
return URL;

是否开启重写日志, 发送至error_log(notice level)

rewrite_log on | off;  
示例:
location /test {
  root /data/nginx/html/pc;
  default_type text/html;
  index index.html;
  if ( $scheme = http ){
      #return 666;
      #return 666 "not allow http";
      #return 301 http://www.baidu.com;
    return 500 "service error";
    echo "if-----> $scheme"; #return后面的将不再执行
}
  if ( $scheme = https ){
   echo "if ----> $scheme";
}

rewrite指令 

1、将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI。

2、注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查。

3、隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示的标志位用于控制此循环机制。

4、如果replacement是以http://或https://开头,则替换结果会直接以重向返回给客户端, 即永久重定向301。

rewrite flag使用介绍  

last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环

break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块后的其它配置;结束循环

redirect:临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;可使用相对路径,或http://或https://开头,此重定向信息不可缓存,状态码:302

permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求,此重定向信息可缓存,状态码:301

last 和 break用法:

break:匹配成功后不再向下匹配,也不会跳转到其他的location,即直接结束匹配并给客户端返回结果数据

last:对某个location的URL匹配成功后会停止当前location的后续rewrite规则,并结束当前location,然后将匹配生成的新URL跳转至其他location继续匹配,直到没有location可匹配后将最后一次location的数据返回给客户端

last实验演练:

1、先在编译安装的nginx服务器进行修改配置文件,实现test1跳转至test2,以及hn跳转至henan。

[root@centos17conf]#vim /apps/nginx/conf/nginx.conf
location /test1 {
              rewrite  ^/test1/(.*)$   /test2/$1 last;
        }
        location  /hn {
              rewrite  ^/hn/(.*)$     /henan/$1  last;      
        }

        location /test2 {
        default_type text/html;
            echo test2;
        }

        location /hn {
        default_type text/html;
            echo henan;                                                                                                                          
        }

 

   2、修改完nginx配置文件之后,重新加载nginx : nginx  -s  reload,并创建hn和test1的文件。

[root@centos17conf]#mkdir /apps/nginx/html/test1
[root@centos17conf]#echo /apps/nginx/html/test1/test1.html > /apps/nginx/html/test1/index.html
[root@centos17conf]#mkdir /apps/nginx/html/hn
[root@centos17conf]#echo /apps/nginx/html/hn/hn.html > /apps/nginx/html/hn/index.html

 3、在客户端开始验证效果:

[root@centos27~]#curl  http://192.168.37.17/hn/
henan
[root@centos27~]#curl  http://192.168.37.17/test1/
test2

网页访问效果:

 break用法:

1、在nginx服务器中修改成break用法的配置文件,实现hn跳转至henan ,修改完配置文件之后进行重新加载:nginx  -s reload

 vim /apps/nginx/conf/nginx.conf

        location /test1 {
              rewrite  ^/test1/(.*)$   /test2/$1 last;
        }
        location  /hn {
              rewrite  ^/hn/(.*)$     /henan/$1  break;   实现hn跳转到henan页面,只会在本location跳转,不会跳转至下一个Location,如果本地没有henan对应的html文件,就会提示无法找到文件。                                                                                       
        }

        location /test2 {
        default_type text/html;
            echo test2;
        }

        location /henan {
        default_type text/html;
            echo henan;
        }

 2、如果nginx服务端的/apps/nginx/html/目录下不新建一个henan目录及henan目录下的html文件,就会提示403错误信息,只会在本地的location跳转,不会跳转至下一个location,如果匹配到就会直接返回给用户,如果没有就会显示错误。 

[root@centos17conf]#mkdir /apps/nginx/html/henan   新建henan目录
[root@centos17conf]#echo /apps/nginx/html/henan/index.html > /apps/nginx/html/henan/index.html 在henan目录下新建一个html文件

  3、在客户端访问网页效果:

[root@centos27~]#curl  http://192.168.37.17/hn/
henan

 permanent永久重定向用法:

1、在nginx服务器端修改配置文件,实现pernanent永久重定向,并重新加载服务:

vim /apps/nginx/conf/nginx.conf

 location  /henan {
       rewrite  ^/henan/(.*)$     /hn/$1  permanent;     
       default_type text/html;
       echo henan;
}

 2、在网页访问效果, 此时已经实现了永久跳转的效果。

总结:301和302可以在用户访问的页面跳转,用户可以直观的看到跳转,而last和break是后端跳转,用户无法发现,301和302实际中用的比较多。 

rewrite案例-自动跳转https

要求:基于通信安全考虑公司网站要求全站https,因此要求将在不影响用户请求的情况下将http请求全部自动跳
转至https,另外也可以实现部分location跳转。

1、在nginx服务端修改配置文件,实现http跳转至https加密,修改完成之后重新加载ngixn服务:nginx  -s reload

server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.net;
    root /data/site1/;                                                                                                                           
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;                                                                                                                     
    access_log  /var/log/nginx/access_json.log  access_json;
    location / {
        if ( $scheme = http ) {     判断scheme如果是http,就跳转至https网站,进行加密设置。
        rewrite ^/(.*)$  https://www.magedu.net/$1  redirect;    实现临时重定向
        }
    }
}

2、在nginx服务端新建一个site1目录,并在此目录下新建一个html文件。

[root@centos27~]#mkdir /data/site1
[root@centos27~]#echo /data/site1/test.html > /data/site1/index.html

3、在客户端验证效果:

[root@centos17~]#curl -IL -k http://www.magedu.net
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.16.1
Date: Sun, 15 Dec 2019 02:43:15 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Keep-Alive: timeout=65
Location: https://www.magedu.net/

HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Sun, 15 Dec 2019 02:43:15 GMT
Content-Type: text/html
Content-Length: 20
Last-Modified: Fri, 13 Dec 2019 04:12:32 GMT
Connection: keep-alive
Keep-Alive: timeout=65
ETag: "5df30fb0-14"
Accept-Ranges: bytes

[root@centos17~]#curl -L -k http://www.magedu.net   忽略秘钥验证检查结果
/data/site1/test.html/

实现多个网站的跳转至https加密网站 

1、nginx服务器端:在/etc/pki/tls/certs目录下修改Makefile配置文件,将生成后的证书文件不进行加密。

[root@centos27certs]#cd /etc/pki/tls/certs
[root@centos27certs]#vim Makefile 

 2、在nginx服务器端,开始自签名证书

[root@centos27certs]#make magedu.org.crt
umask 77 ; \
#/usr/bin/openssl genrsa -aes128 2048 > magedu.org.key
/usr/bin/openssl genrsa  2048 > magedu.org.key
Generating RSA private key, 2048 bit long modulus
.......+++
......+++
e is 65537 (0x10001)
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key magedu.org.key -x509 -days 365 -out magedu.org.crt 
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:beijing             
Locality Name (eg, city) [Default City]:beijing
Organization Name (eg, company) [Default Company Ltd]:magedu.org
Organizational Unit Name (eg, section) []:opt
Common Name (eg, your name or your server's hostname) []:www.magedu.org
Email Address []:

 3、在nginx服务端修改配置文件,原来已经添加了一个网站:www.magedu.net,此时新添加一个需要加密的网站:www.magedu.org                                                                                 

server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.net;
    root /data/site1/;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log  /var/log/nginx/access_json.log  access_json;
    location / {
        if ( $scheme = http ) {
        rewrite ^/(.*)$  https://www.magedu.net/$1  redirect;
        }
    }
}
    

server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.org;   新添加一个网址
    root /data/site2/;
    ssl_certificate /etc/nginx/ssl/magedu.org.crt;  指定证书路径
    ssl_certificate_key /etc/nginx/ssl/magedu.org.key; 指定私钥路径
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;                                                                                                                     
    access_log  /var/log/nginx/magedu_org.access_json.log  access_json;
    location / {
        if ( $scheme = http ) {
        rewrite ^/(.*)$ https://www.magedu.org/$1 redirect;
        }
    }                                                                                                                                            
}

在nginx服务器上访问的html文件和存放证书、私钥的目录,并将证书和私钥文件存在指定的ssl目录下

[root@centos27site2]#mkdir /etc/nginx/ssl
[root@centos27site2]#echo /data/site2/test2.html > /data/site2/index.html
[root@centos27site2]#mv magedu.org* /data/ssl
[root@centos27site2]#mv magedu.org.* /etc/nginx/ssl/

 4、在客户端验证效果,此时访问新的网站也可以访问。

[root@centos17~]#curl -L -k www.magedu.org
/data/site2/test2.html

 rewrite案例-判断文件是否存在

 1、修改nginx服务的配置文件,判断访问的文件是否存在,如果不存在,就跳转至www.magedu.net网页下访问。

server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.net;
    root /data/site1/;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;                                                                                                                     
    access_log  /var/log/nginx/access_json.log  access_json;
    location / {                   
        if ( !-f $request_filename ) {       判断文件是否存在,不存在就跳转至www.magedu.net网页下,其中-f和-e区别:-e判断文件存在性,-f判断普通文件是否存在。
        rewrite ^/(.*)$  https://www.magedu.net/index.html  redirect;   如果判断文件性,用-e选项,则index.html文件不需要加,如果-f选项,就需要加上默认的index.html文件                                                                                    
        }
    }
}

 2、修改完ngixn配置文件之后,然后重新加载nginx服务:nginx  -s reload,并在指定的/data/site1目录下新建一个index.html文件。

[root@centos27site1]#mkdir /data/site1
[root@centos27site1]#echo  /data/site1/test.html  > /data/site1/index.html

  3、验证效果,此时网址后面输错内容,就会跳转到加密的网址后面。

[root@centos17apps]#curl -L -k https://www.magedu.net/xxx.html
/data/site1/test.html

rewrite 生产案例

要求:将 http:// 请求跳转到 https://

location / {
  if ($scheme = http ) {
   rewrite / https://www.magedu.net/ redirect;
 }
}

 要求:当用户访问到公司网站的时输入了一个错误的URL,可以将用户重定向至官网首页

location / {
root /data/nginx/html/pc;
  index index.html;
  if (!-f $request_filename) {
  #return 404 "No exsit";
  rewrite (.*) http://www.magedu.net/index.html;
  }
}

   Nginx防盗链   

      防盗链基于客户端携带的referer实现,referer是记录打开一个页面之前记录是从哪个页面跳转过来的标记信息,如
果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗链,referer就是之前的
那个网站域名,正常的referer信息有以下几种:

ngx_http_referer_module模块:
用来阻止Referer首部无有效值的请求访问,可防止盗链。
valid_referers none|blocked|server_names|string ...;
定义referer首部的合法可用值,不能匹配的将是非法值
none:请求报文首部没有referer首部
blocked:请求报文有referer首部,但无有效值
server_names:referer首部中包含本主机名
arbitrary_string:任意字符串,但可使用*作通配符
regular expression:被指定的正则表达式模式匹配到的字符串,要使用~开头,例如: ~.*\.magedu\.com

 实现web盗链 

1、先创建两个网址,分别是www.magedu.net和www.magedu.org,此时实现net网站盗用org网站的图片。

vim /etc/nginx/conf.d/test.conf

server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.net;
    root /data/site1/;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log  /var/log/nginx/access_json.log  access_json;

    location / {
        if ( !-e  $request_filename )  {
        rewrite ^/(.*)$  http://www.magedu.net/   redirect;                                                                                      
        }
    }
}


server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.org;
    root /data/site2/;
    ssl_certificate /etc/nginx/ssl/magedu.org.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.org.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log  /var/log/nginx/magedu_org.access_json.log  access_json;
}

  在/data/site1目录下,创建一个盗链网站:

  vim  /data/site1/daolian.html

盗链
<img src=http://www.magedu.org/sun.jpg>  

 2、此时访问magedu.net/daolian.html网站,此时就是盗链了magedu.org网站的sun.jgp图片。

[root@centos17apps]#curl http://www.magedu.net/daolian.html
盗链
<img src=http://www.magedu.org/sun.jpg>

实现防盗链

基于访问安全考虑,nginx支持通过ungx_http_referer_module模块 https://nginx.org/en/docs/http/ngx_http_re
ferer_module.html#valid_referers 检查访问请求的referer信息是否有效实现防盗链功能,定义方式如下:

防止盗链生产案例:

valid_referers none block server_names
*.magedu.com magedu.* *.mageedu.com mageedu.* ~\.magedu\. ~\.google\. ~\.baidu\.;
if ($invalid_referer) {
return 403 "Forbidden Access";
}

自定义防止盗链:  

server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.net;
    root /data/site1/;
    ssl_certificate /etc/nginx/ssl/magedu.net.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.net.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log  /var/log/nginx/access_json.log  access_json;

    location / {
        if ( !-e  $request_filename )  {
        rewrite ^/(.*)$  http://www.magedu.net/   redirect;
        }
    }
}


server  {
    listen 443 ssl;
    listen 80;
    server_name www.magedu.org;
    root /data/site2/;
    ssl_certificate /etc/nginx/ssl/magedu.org.crt;
    ssl_certificate_key /etc/nginx/ssl/magedu.org.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    access_log  /var/log/nginx/magedu_org.access_json.log  main;
    valid_referers none block server_names *.magedu.com  ~\.google\. ~\.baidu\.;   定义有效referer;除了定义的这个通配符、正则表达式的网址可以调用,其他网址都不可以调用本网址的资源                                                              
    if ($invalid_referer) {   出定义的referer外,其他网址就会返回状态:错误403
    return 403 "Forbidden Access";
    }
}

 重启nginx进行访问测试。  

Guess you like

Origin www.cnblogs.com/struggle-1216/p/12033392.html