1. 程式人生 > >php runtime 中 http web 中 rewrite 淺解和方案

php runtime 中 http web 中 rewrite 淺解和方案

本文針對函式計算的 php runtime web 相關運用開發, 提供一個簡單實現url rewrite的方案,在介紹方案之前,我們先看看相關的幾個概念: 偽靜態頁面,動態頁面,rewrite.

php runtime FAQ 列表

偽靜態

  • 靜態網頁
    比如雲棲網站上放了一個abc.html檔案,你想訪問它就直接輸入yunqi. com/abc.html。Web伺服器看到這樣的地址就直接找到這個檔案輸出給客戶端。
  • 動態網頁
    假如你想做一個顯示當前時間的頁面,那麼就可以寫個PHP檔案,然後訪問yunqi. com/abc.php。Web伺服器看到這樣的地址,找到abc.php這個檔案,會交給PHP執行後返回給客戶端。而動態網頁往往要輸入引數,所以地址就變成yunqi. com/abc.php?a=1&b=2。

搜尋引擎比較煩這種帶問號的動態網頁,因為引數可以隨便加,而返回內容卻不變,所以會對這種網頁降權。於是有了mod_rewrite,它可以重新對映地址。

rewrite

比如當前這個頁面的地址 http://www.yunqi.com/post/20153311,Web伺服器收到請求後會重新對映為 www.yunqi.com/post.php?id=20153311,然後再執行那個PHP程式。(以上網址均為假設)這樣,在內部不改變的情況下,對外呈現出來的網址變成了沒有問號的象靜態網頁的網址一樣。於是有人給起了個名字叫“偽靜態”。其實也沒什麼偽的,就是沒有問號的靜態網址,讓搜尋引擎舒服點而已。

函式計算 php runtime 簡單實現 rewrite 的一種方法

先以簡單的nginx 中的一個簡單的 rewrite 為例:

location ~ ^/(\w+)$ {
    rewrite /index.php?sub=$1;
}

location ~ ^/post/(\w+)/(\d+)$ {
    rewrite /post.php?class=$1&id=$2;
}

php url rewrite 簡單實現

<?php

function rewrite_urls($s) 
{
    $in = array(
      '|^/post/(\\w+)/(\\d+)$|',
      '|^/(\\w+)$|'
    );

    $out = array(
      '/post.php?class=$1&id=$2',
      '/index.php?sub=$1',
    
    );
    return preg_replace($in, $out, $s); 
}

$post_url = '/post/literatrue/34';
echo rewrite_urls($post_url) .PHP_EOL;

$index_url = '/admin';
echo rewrite_urls($index_url) .PHP_EOL;

執行輸出結果:

/post.php?class=literatrue&id=34
/index.php?sub=admin

因此在使用 php runtime的時候,根據收到請求的uri(假設是/post/literatrue/34), 執行 rewrite_urls 函式(rewrite 規則填寫在這個函式的 $in$out 中), 然後將 rewrite 後的 uri (/post.php?class=literatrue&id=34) 作為呼叫 fcPhpCgiProxy.requestPhpCgi 函式時,傳入引數 $fastCgiParams 的一對 key-value; 有關 fcPhpCgiProxy 可以參考 #683415#640912 介紹 fcPhpCgiProxy 的部分。

參考:

https://www.zhihu.com/question/20153311/answer/14147350
https://www.smashingmagazine.com/2011/11/introduction-to-url-rewriting/