溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Nginx Rewrite的實現(xiàn)原理和使用方法

發(fā)布時間:2020-06-16 15:06:11 來源:億速云 閱讀:395 作者:元一 欄目:系統(tǒng)運維

一、理論講解

1.1Nginx Rewrite簡介

Nginx Rwrite即Nginx服務(wù)的規(guī)則重寫,主要的功能是實現(xiàn)瀏覽器訪問HTTP URL的跳轉(zhuǎn),其中相關(guān)的正則表達式是基于Perl語言。一般來說,幾乎所有的Web服務(wù)器都支持URL重寫。

Rewrite是一種服務(wù)器的重寫 技術(shù),它可以使得服務(wù)器可以支持 URL 重寫,是一種最新流行的服務(wù)器技術(shù)。它還可以實現(xiàn)限制特定IP訪問網(wǎng)站的功能。很多情況下,某個 IP 的訪問很容易造成 CPU 100% (比如 某些搜索引擎的固定抓取,別人大量的采集站點),這個時候我們就要利用一些有效的手段封掉對方的 IP,讓他無法消耗服務(wù)器的資源,封 IP 的方法有很多種,如果你的 Web 服務(wù)器安裝了 Rewrite 模塊的話,也可以試試利用 Rewrite 規(guī)則封掉對方的 IP。

1.1.1什么是URL?

對于百度給出的定義如下:URL(Uniform Resource Locator),統(tǒng)一資源定位符。這樣的表述似乎過于抽象,因為可能根本不了解什么是“統(tǒng)一資源定位符”?其實我們可以將URL簡易地理解為你所需要通過網(wǎng)絡(luò)獲取資源的地址,(URL)是由一串字符組成,這些字符可以是字母,數(shù)字和特殊符號。

具體實例如下:

php+HTML
http://www.wangluopx.cn/yunwei/gz/zz/2018-07-03/1940.html

其具體結(jié)構(gòu)在這就不做詳細闡述了,有興趣可以自行查閱相關(guān)文檔。

1.1.2“跳轉(zhuǎn)”有什么用?

跳轉(zhuǎn)需要根據(jù)具體的應(yīng)用場景才能真正體會到nginx規(guī)則重寫實現(xiàn)網(wǎng)頁跳轉(zhuǎn)的作用。稍后會根據(jù)不同的應(yīng)用場景進行對應(yīng)的操作與設(shè)置。一般來說,實現(xiàn)跳轉(zhuǎn)的作用可以總結(jié)為以下幾個方面:

  1. 調(diào)整用戶瀏覽的URL,使其規(guī)范;
  2. 使搜索引擎收錄網(wǎng)站內(nèi)容,提升用戶的使用體驗;
  3. 隱藏網(wǎng)站URL真實地址等;

1.1.3Perl是什么語言?

Perl,一種功能豐富的計算機程序語言,運行在超過100種計算機平臺上,適用廣泛,從大型機到便攜設(shè)備,從快速原型創(chuàng)建到大規(guī)??蓴U展開發(fā)。

Perl借取了C、sed、awk、shell腳本語言以及很多其他程序語言的特性,其中最重要的特性是它內(nèi)部集成了正則表達式的功能,以及巨大的第三方代碼庫CPAN。簡而言之,Perl像C一樣強大,像awk、sed等腳本描述語言一樣方便,被Perl語言愛好者稱之為“一種擁有各種語言功能的夢幻腳本語言”、“Unix中的王牌工具”。

1.2如何實現(xiàn)Rewrite跳轉(zhuǎn)?

rewrite使用Nginx全局變量或自己設(shè)置的變量,結(jié)合正則表達式和標志位實現(xiàn)URL重寫以及重定向
,基于ngx_http_rewrite_module模塊進行處理。

1.2.1Rwrite 實用場景

Nginx跳轉(zhuǎn)需求的實現(xiàn)方式

●使用rewrite進行匹配跳轉(zhuǎn)
  ●使用if匹配全局變量后跳轉(zhuǎn)
  ●使用location匹配再跳轉(zhuǎn)

rewrite放在server{},if{},location{}段中

對域名或參數(shù)字符串

●使用if全局變量匹配
  ●使用proxy_ pass反向代理

1.2.2命令語法

rewrite <regex> <replacement> [flag];
正則  跳轉(zhuǎn)后的內(nèi)容  rewrite支持的flag

1.2.3location分類

location = patt{}[精準匹配]
location patt{} [一般匹配]
location ~patt{} [正則匹配]
正則匹配的常用表達式

標記                         說明
~           執(zhí)行一個正則匹配,區(qū)分大小寫
~          執(zhí)行一個正則匹配,不區(qū)分大小寫
!~          執(zhí)行一個正則匹配,區(qū)分大小寫不匹配
!~
        執(zhí)行一個正則匹配,不區(qū)分大小寫不匹配
^~          普通字符匹配;使用前綴匹配。如果匹配成功,則不再匹配其他location
=           普通字符精確匹配。也就是完全匹配
@           定義一個命名的location,使用在內(nèi)部定向時

1.2.4location優(yōu)先級

1.相同類型的表達式,字符串長的會優(yōu)先匹配
2.按優(yōu)先級排列
●=類型
●^~類型表達式
●正則表達式(~和~*)類型
●常規(guī)字符串匹配類型,按前綴匹配
●通用匹配(/) ,如果沒有其它匹配,任何請求都會匹配到

1.2.5比較rewrite和location

1.相同點
●都能實現(xiàn)跳轉(zhuǎn)
2.不同點
●rewrite是在同一域名內(nèi)更改獲取資源的路徑
●location是對一類路徑做控制訪問或反向代理,還可以proxy_ pass
到其他機器
3.rewrite會寫在location里,執(zhí)行順序:
●執(zhí)行server塊里面的rewrite指令
●執(zhí)行l(wèi)ocation匹配
●執(zhí)行選定的location中的rewrite指令

1.2.6location優(yōu)先級規(guī)則

匹配某個具體文件
●(location =完整路徑) > (location ^~完整路徑) > (location ~完整
路徑) > (location ~完整路徑) > (location 完整路徑) > (location /)
用目錄做匹配訪問某個文件
●(location=目錄) > (location ^~目錄/) > (location~目錄) >
(location ~
目錄) > (location 目錄) > (location /)

二、根據(jù)不同應(yīng)用場景下實現(xiàn)Nginx Rewrite的配置實例

首先我們先安裝好域名解析named服務(wù)包——bind以及nginx服務(wù)(也可以使用手工編譯,這里我們使用yum直接安裝)

1.安裝bind設(shè)置配置文件(三個)并開啟服務(wù)

[root@localhost ~]# yum install bind -y
[root@localhost named]# netstat -napt | grep named
tcp        0      0 192.168.68.145:53       0.0.0.0:*               LISTEN      6077/named          
tcp        0      0 127.0.0.1:53            0.0.0.0:*               LISTEN      6077/named          
tcp        0      0 127.0.0.1:953           0.0.0.0:*               LISTEN      6077/named          
tcp6       0      0 ::1:53                  :::*                    LISTEN      6077/named          
tcp6       0      0 ::1:953                 :::*                    LISTEN      6077/named

2.安裝nginx

我們會看到直接使用yum安裝無法成功的

[root@localhost ~]# yum install -y nginx
已加載插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.cn99.com
 * extras: mirrors.cn99.com
 * updates: mirrors.cn99.com
沒有可用軟件包 nginx。
錯誤:無須任何處理
[root@localhost ~]# rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
獲取http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
警告:/var/tmp/rpm-tmp.aXVptL: 頭V4 RSA/SHA1 Signature, 密鑰 ID 7bd9bf62: NOKEY
準備中...                          ################################# [100%]
正在升級/安裝...
   1:nginx-release-centos-7-0.el7.ngx ################################# [100%]
[root@localhost ~]# yum install -y nginx
...省略部分內(nèi)容

3.檢查安裝是否成功,查看配置文件目錄

[root@localhost ~]# rpm -q nginx
nginx-1.16.1-1.el7.ngx.x86_64
[root@localhost ~]# rpm -qc nginx
/etc/logrotate.d/nginx
/etc/nginx/conf.d/default.conf   #這是我們待會做rewrite需要配置更改的文件
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/win-utf
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug

2.1 rewrite規(guī)則配置應(yīng)用場景一:基于域名的跳轉(zhuǎn)

簡單解釋一下該場景:某公司出于某些原因需要將舊的域名修改為新的域名,但是新的域名大家都比較陌生,所以就需要進行舊——新的跳轉(zhuǎn),即:客戶機上訪問該舊的域名時可以自動跳轉(zhuǎn)到新的域名,客戶經(jīng)過多次訪問,發(fā)現(xiàn)只要輸入新的域名就能訪問了,而且輸入更加簡單友好。

下面我們結(jié)合上述的場景來具體闡述如何進行配置:

1.首先我們是yum安裝的,上面已經(jīng)注釋了其主配置文件(是一個默認的配置文件,功能必然沒有手工編譯豐富):/etc/nginx/conf.d/default.conf,簡要介紹一下其文件內(nèi)容結(jié)構(gòu)

[root@localhost named]# cd /etc/nginx/conf.d/
[root@localhost conf.d]# ls
default.conf
[root@localhost conf.d]# cat default.conf 
server {
    listen       80;                           #監(jiān)聽端口
    server_name  localhost;                    #域名,一般是指服務(wù)器的域名

    #charset koi8-r;                          #字符設(shè)置 
    #access_log  /var/log/nginx/host.access.log  main;      #訪問日志路徑設(shè)置

    location / {    #location 有”定位”的意思, 根據(jù)Uri來進行不同的定位,Uri可以理解為資源對應(yīng)于URL是地址
        root   /usr/share/nginx/html;      
        index  index.html index.htm;
    }
    #location可以把網(wǎng)站的不同部分,定位到不同的處理方式上

    #error_page  404              /404.html;    #404訪問錯誤頁面找不到

    # redirect server error pages to the static page /50x.html           
    #
    error_page   500 502 503 504  /50x.html;              #錯誤頁面,服務(wù)器出問題
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

2.更改配置操作:更改域名、域名重定向

 server {
    listen       80;                    
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        if ($host = 'www.lokott.com'){
                rewrite ^/(.*)$ http://www.newlokott.com/$1 permanent;
        }

3.開啟nginx服務(wù)關(guān)閉防火墻

[root@localhost conf.d]# systemctl start nginx
[root@localhost conf.d]# systemctl stop firewalld.service 
[root@localhost conf.d]# setenforce 0

4.測試是否正常跳轉(zhuǎn)

在win10上輸入舊的域名:www.lokott.com是否正常跳轉(zhuǎn)為www.newlokott.com

舊域名輸入界面,按完回車后跳轉(zhuǎn)為下面第二張界面,可以驗證的確將舊域名跳轉(zhuǎn)到新的域名了。

Nginx Rewrite的實現(xiàn)原理和使用方法

Nginx Rewrite的實現(xiàn)原理和使用方法

2.2  rewrite規(guī)則配置應(yīng)用場景二:基于ip地址

簡單描述:公司網(wǎng)頁正在做維護或者結(jié)構(gòu)調(diào)整,目前只允許合法的ip地址訪問公司的頁面,其他的就跳轉(zhuǎn)到維護或者其他頁面。

具體配置:

1.設(shè)置一個合法的標志位;set $rewrite true;

2.判斷是否是合法的IP,是就正常跳轉(zhuǎn),否則跳轉(zhuǎn)為main.html頁面;

[root@localhost ~]# vim /etc/nginx/conf.d/default.conf 
[root@localhost ~]# cat /etc/nginx/conf.d/default.conf 
server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    set $rewrite true;                      #由此開始配置場景二
    if ($remote_addr = "192.168.68.151"){
        set $rewrite false;
    }   

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

    location = /main.html {
        root /usr/share/nginx/html;
    }                                       #到此配置二結(jié)束

    location / {
        #if ($host = 'www.lokott.com'){     #注釋場景一的配置
        #       rewrite ^/(.*)$ http://www.newlokott.com/$1 permanent;
        #}
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

3.將main.html頁面寫到/usr/share/nginx/html/下

[root@localhost ~]# cd /usr/share/nginx/html/
[root@localhost html]# ls
50x.html  index.html
[root@localhost html]# echo "this is a maintenance web page" > main.html
[root@localhost html]# ls
50x.html  index.html  main.html

4.重啟nginx服務(wù),然后之后檢驗

[root@localhost html]# systemctl restart nginx
[root@localhost html]# netstat -antp | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      64979/nginx: master 

5.根據(jù)上面的配置,結(jié)果應(yīng)該是IP地址為192.168.68.151的主機是可以正常訪問的,其他的則無法訪問。

實際的結(jié)果如下:

Nginx Rewrite的實現(xiàn)原理和使用方法

換一臺centos虛擬機測試則無法訪問正常的頁面

Nginx Rewrite的實現(xiàn)原理和使用方法

下面,我們對于剛剛配置文件的內(nèi)容做邏輯層面上的梳理與對應(yīng)解釋:

截取關(guān)鍵部分的配置命令:

set $rewrite true;                      #設(shè)置一個標志位用來進行不同的判斷從而觸發(fā)不同的操作過程
if ($remote_addr = "192.168.68.151"){   #判斷請求訪問的主機ip地址是否是被允許的(只有該地址有權(quán)限進行正常訪問)
set $rewrite false;                           #更改標志位的值,從而不觸發(fā)原本為true的操作,即不執(zhí)行下面兩段的操作
}

if ($rewrite = true){                                 #若是非法地址訪問則該標志位仍然為true,從而執(zhí)行該段內(nèi)容
rewrite (.+) /main.html;
}

location = /main.html {           #基于上面的true匹配在精確匹配進行具體操作執(zhí)行的定位,訪問的是維護頁面
root /usr/share/nginx/html;
}

所以根據(jù)邏輯上的理解,我們知道只有被設(shè)置為允許的ip地址的客戶機才能正常訪問公司頁面,則其他的沒有改權(quán)限,相當于做了一個“白名單”。

2.3  rewrite規(guī)則配置應(yīng)用場景三:基于跳轉(zhuǎn)到新域名后面有目錄的情況

場景簡述:加入訪問的是www.lokott.com/p,現(xiàn)在需要將這個域名下面的發(fā)帖都跳轉(zhuǎn)到bbs.lokott.com/ss/p,

1.我們?nèi)匀粚δJ主配置文件進行修改

[root@localhost ~]# cat /etc/nginx/conf.d/default.conf 
server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    set $rewrite true;
    if ($remote_addr = "192.168.68.151"){
        set $rewrite false;
    }   

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

    location = /main.html {
        root /usr/share/nginx/html;
    }

    location /p {                                      #第三個場景配置
        rewrite (.+) http://bbs.lokott.com/ss$1 permanent;    
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重啟服務(wù)

[root@localhost html]# systemctl restart nginx

3.在win10虛擬機上測試

Nginx Rewrite的實現(xiàn)原理和使用方法

Nginx Rewrite的實現(xiàn)原理和使用方法

由此現(xiàn)象可見,上述$1的含義是:你所定義的location的/p目錄之后的內(nèi)容,具體為何需要你自己創(chuàng)建站點,例如:

在/usr/local/nginx/html目錄下創(chuàng)建ss/p/index.html網(wǎng)頁,網(wǎng)頁內(nèi)容為“hello world” ,在使用http://www.lokott.com/p/index訪問時將會如下圖跳轉(zhuǎn):

Nginx Rewrite的實現(xiàn)原理和使用方法

2.4  rewrite規(guī)則配置應(yīng)用場景四:基于多參數(shù)匹配

場景簡述:在訪問www.lokott.com域名時在后面輸入已經(jīng)規(guī)定的參數(shù),實現(xiàn)規(guī)則跳轉(zhuǎn),例如:輸入http://www.lokott.com/100-200-4454.html則跳到首頁

1.更改配置文件

server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    if ($request_uri ~ ^/100-(100|200)-(\d+).html$){     #第四個場景
        rewrite (.*) http://www.lokott.com permanent;      //
    }
    #上述涉及的正則:^——開頭 | 或   \ 轉(zhuǎn)義  d+ 數(shù)字匹配
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重啟服務(wù)

[root@localhost html]# systemctl restart nginx
[root@localhost html]# echo "asda" > 100-200-4454.html
[root@localhost html]# ls
100-200-4454.html  50x.html  index.html 
[root@localhost html]# echo "asda" > 100.html

3.測試驗證

Nginx Rewrite的實現(xiàn)原理和使用方法

Nginx Rewrite的實現(xiàn)原理和使用方法

在站點目錄在創(chuàng)建一個100.html文件,內(nèi)容為asda,然后進行測試,結(jié)果如下:

Nginx Rewrite的實現(xiàn)原理和使用方法

2.5 rewrite規(guī)則配置應(yīng)用場景五:基于文件后綴名訪問

場景簡述:訪問upload目錄下的php文件時跳轉(zhuǎn)至主頁面

1.修改配置文件

server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location ~* /upload/.+\.php$ {                       #第五個場景
        rewrite (.+) http://www.lokott.com permanent;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重啟服務(wù)

[root@localhost html]# systemctl restart nginx

3.測試驗證

Nginx Rewrite的實現(xiàn)原理和使用方法

跳轉(zhuǎn)的頁面:

Nginx Rewrite的實現(xiàn)原理和使用方法

2.6 rewrite規(guī)則配置應(yīng)用場景六:基于指定文件(具體頁面)匹配

場景簡述:訪問固定的頁面時跳轉(zhuǎn)到首頁

1.修改配置文件

server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location ~* ^/abc/123.html {                         #第六個場景
        rewrite (.+) http://www.lokott.com permanent;
    }
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重啟服務(wù)

[root@localhost html]# systemctl restart nginx

3.測試驗證

Nginx Rewrite的實現(xiàn)原理和使用方法

跳轉(zhuǎn)頁面如下:

Nginx Rewrite的實現(xiàn)原理和使用方法

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI