PHP教學-利用 .htaccess 來改變 php 副檔名

為了安全性或是其他原因,常常看到許多網站的 URL 將實際檔案的路徑隱藏起來,比如說下方的 URL 我們就看不出該網頁是用什麼程式寫的,PHP 或是 ASP?
http://www.blogger.com/post-create.g?blogID=27977601

舉個簡單的例子,如果我們想把網址中的副檔名 php 改成 htm。
開啟 http://localhost/test.htm 實際上是連到 http://localhost/test.php
實作步驟如下:

    檢察 apahce 的 httpd.conf 這一行是否開啟 ( 以xampp為例預設是開啟的 ) :

        LoadModule rewrite_module modules/mod_rewrite.so

    在你要改寫 URL 的檔案資料夾中,放入一個檔案取名為 .htaccess,寫入以下內容,這樣就算是完成了,不必重新啟動 apache

        RewriteEngine on
        RewriteRule ^(.*)\.htm$ $1.php [nc]


RewriteRule 這行的語法就是源自於 Perl 的 Regular Expression (正規表達式),在 PHP 和 Javascript 也常常用到。

$1 表示使用 RewriteRule 的第一個 Regular Expression (是否就是指 ^(.*)\.htm$ 這段?)
[nc] 代表 not case sensitive (大小寫視為相同)

------------------------------
還有其他比較複雜的範例 ,如果你也像我一樣不熟悉正規表達式,可以直接拿這些例子修改 :

1) 網址 product-12.html => 實際路徑 product.php?id=12

    RewriteEngine on
    RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1


2) 網址 product/ipod-nano/12.html => 實際路徑 product.php?id=12

    RewriteEngine on
    RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2


3) 把不含 www 的 URL 加上 www (http://test.com/ => http://www.test.com/)

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^optimaxwebsolutions\.com$
    RewriteRule (.*) http://www.optimaxwebsolutions.com/$1 [R=301,L]


4) 網址 yoursite.com/xyz => 實際路徑 yoursite.com/user.php?username=xyz

    RewriteEngine On
    RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
    RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1


5) 把某個資料夾的路徑,改連到另一個資料夾底下

假設你要翻新整個網站 root 資料夾中的內容,你可以先在 root 資料夾的裡面開一個 new 資料夾,在 root/new 裡面編輯新的網頁。然後使用以下的 rewrite rule 把 http://root/ 指向 http://root/new/

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
    RewriteCond %{HTTP_HOST} ^www\.test\.com$
    RewriteCond %{REQUEST_URI} !^/new/
    RewriteRule (.*) /new/$1

留言

這個網誌中的熱門文章

c語言-關於#define用法

PHP教學 - 資料型態(Data Type) - 上

CMD常用網管指令