在這篇,我要記錄 Rewrite 的使用方法,此外,有需要的朋友也可以透過我的記錄的方法來運用
首先,我們要先開啟 httpd.conf 的相關設定,才能順利使用

 

cent os:(可用root權限登入)

vim /etc/httpd/conf/httpd.conf

ubuntu:

su vim /etc/apache2/httpd.conf

 

進入 httpd.conf 按 / 鍵入以下的文字就能順利找到

 

#LoadModule rewrite_module modules/mod_rewrite.so

 

按 insert 將 # 刪除,再按 esc 後鍵入 wq  enter (儲存+離開)
重啟 apapche2

 

cent os : /etc/init.d/httpd restart

ubuntu: /etc/init.d/apache2 restart

 

接著要在主機目錄裡新增一個名叫  .htaccess  的檔案,這裡面包含了你想變換的規則
那這個 .htaccess 要放在哪裡,就放在你要控制的資料夾裡,例:www.zzz.com/bbb/ (那就放在 bbb 資料夾當中即可)
當你在主機裡開啟了一個新檔案取名為 .htaccess 後,在編輯畫面裡可輸入以下規則(rules)

 

RewriteEngine On
RewriteBase /oeya/
RewriteRule ^product/(\w+)/?$ product.php?id=$1
RewriteRule ^product-([0-9a-zA-Z]+)\.html$ product.php?id=$1


說明

 

引擎開啟
底層目錄
第一條規則 顯示結果(把檔案product.php偽裝成目錄product/) $ 來源網址
第二條規則 顯示結果(把檔案product.php偽裝成product-變數值.html) $ 來源網址
([0-9a-zA-Z]+)=正規化表示,容許0~9、a~z、A~Z的文字、數字


----------------------以上基礎設置完成--------------------

 

回到 client端(客戶端) 程式頁面,你可以先做測試,新建一個檔名 test.php
開啟 test.php貼上

 


<?php
// Get the username from the url
$id = $_GET['id'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Simple mod\_rewrite example</title>
    <style type="text/css"> .green { color: green; } </style>
</head>
<body>
  <h1>You Are on user.php!</h1>
  <p>Welcome: <span><?php echo $id; ?></span></p>
</body>
</html>

 

在網址列上輸入 http://localhost/test/123         相等 http://localhost/test.php?id=123
                      http://localhost/test-123.html

我自己測試的結果,html 的方式讓我在對應變數、css 的時候會是正確的

arrow
arrow
    全站熱搜

    六睏 發表在 痞客邦 留言(0) 人氣()