偽靜態(tài)
靜態(tài)網(wǎng)頁(yè)
比如xxx網(wǎng)站上放了一個(gè)abc.html文件,你想訪問(wèn)它就直接輸入xxx. com/abc.html。Web服務(wù)器看到這樣的地址就直接找到這個(gè)文件輸出給客戶端。
動(dòng)態(tài)網(wǎng)頁(yè)
假如你想做一個(gè)顯示當(dāng)前時(shí)間的頁(yè)面,那么就可以寫個(gè)PHP文件,然后訪問(wèn)xxx. com/abc.php。Web服務(wù)器看到這樣的地址,找到abc.php這個(gè)文件,會(huì)交給PHP執(zhí)行后返回給客戶端。而動(dòng)態(tài)網(wǎng)頁(yè)往往要輸入?yún)?shù),所以地址就變成xxx. com/abc.php?a=1&b=2。
搜索引擎比較煩這種帶問(wèn)號(hào)的動(dòng)態(tài)網(wǎng)頁(yè),因?yàn)閰?shù)可以隨便加,而返回內(nèi)容卻不變,所以會(huì)對(duì)這種網(wǎng)頁(yè)降權(quán)。于是有了mod_rewrite,它可以重新映射地址。
rewrite
Rewrite是一種服務(wù)器的重寫技術(shù),它可以使得服務(wù)器可以支持 URL 重寫,是一種最新流行的服務(wù)器技術(shù)。它還可以實(shí)現(xiàn)限制特定IP訪問(wèn)網(wǎng)站的功能
比如當(dāng)前這個(gè)頁(yè)面的地址 http://www.xxx.com/post/20153311,Web服務(wù)器收到請(qǐng)求后會(huì)重新映射為 www.xxx.com/post.php?id=20153311,然后再執(zhí)行那個(gè)PHP程序。(以上網(wǎng)址均為假設(shè))這樣,在內(nèi)部不改變的情況下,對(duì)外呈現(xiàn)出來(lái)的網(wǎng)址變成了沒(méi)有問(wèn)號(hào)的象靜態(tài)網(wǎng)頁(yè)的網(wǎng)址一樣。于是有人給起了個(gè)名字叫“偽靜態(tài)”。其實(shí)也沒(méi)什么偽的,就是沒(méi)有問(wèn)號(hào)的靜態(tài)網(wǎng)址,讓搜索引擎舒服點(diǎn)而已。
函數(shù)計(jì)算 php runtime 簡(jiǎn)單實(shí)現(xiàn) rewrite 的一種方法
先以簡(jiǎn)單的nginx 中的一個(gè)簡(jiǎn)單的 rewrite 為例:
location ~ ^/(\w+)$ {
rewrite /index.php?sub=$1;
}
location ~ ^/post/(\w+)/(\d+)$ {
rewrite /post.php?class=$1&id=$2;
}
php url rewrite 簡(jiǎn)單實(shí)現(xiàn)
<?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;
執(zhí)行輸出結(jié)果:
/post.php?class=literatrue&id=34 /index.php?sub=admin
因此在使用 php runtime的時(shí)候,根據(jù)收到請(qǐng)求的uri(假設(shè)是/post/literatrue/34), 執(zhí)行 rewrite_urls 函數(shù)(rewrite 規(guī)則填寫在這個(gè)函數(shù)的 $in 和 $out 中), 然后將 rewrite 后的 uri (/post.php?class=literatrue&id=34) 作為調(diào)用 fcPhpCgiProxy.requestPhpCgi 函數(shù)時(shí),傳入?yún)?shù) $fastCgiParams 的一對(duì) key-value。