Apache Rewrite with Htaccess

參考網址:

Apache Rewrite with Htaccess 理解與技巧

.htaccess (YuYan’s example):

#開啟 Rewrite
RewriteEngine On

#http://www.gwinstek.com.tw/tw/faq/faqquestionlist.aspx?bid=33
#to
#https://www.gwinstek.com/en-global/faq/index?cate=55&subcate=92&ser=82&key=
RewriteCond ${REQUEST_URI} ^/tw/faq/faqquestionlist.aspx
RewriteCond ${QUERY_STRING} bid=33
RewriteRule ^tw/faq/faqquestionlist.aspx(.*) en-global/faq/index?cate=55&subcate=92&ser=82&key= [R=301,L]

#http://www.gwinstek.com/en-global/FaqSearch/faqs
#to
#https://www.gwinstek.com/en-global/faq/index
RewriteCond ${REQUEST_URI} ^/en-global/FaqSearch/faqs
RewriteRule ^en-global/FaqSearch/faqs(.*) /en-global/faq/index$1 [R=301,L]
(下略)

Note

    OS為Centos Apache 2.2,利用 .htaccess 進行轉址。 
    多個RewriteCon 配一個RewriteRule(也可以多個)
    ^ 表示前段匹配
    -f 表示文件是否存在flag
    -d 表示資料夾是否存在
    [R=301,L]  R表示回應的HTTP code 通常為301 or 302, 
    L表示如果做完就不會再進行Rewrite 動作(類似 C 語言的return)

    RewriteCond [test_string] [match_string] [flags]
    RewriteRule …
            - test_string:要比對的條件
            - match_string:符合的條件

    %{REQUEST_URI}:Domain 後面完整的 URI Path,Rule 其實會拿到不完整的 URI,詳情可以參考「五、一些小特性」段落
    %{QUERY_STRING}:後面 GET 帶的參數
    %{HTTP_HOST}:Domain
    %{HTTP_COOKIE}:Cookie
    %{HTTPS}:判斷是否用 https 或 http,如果是 https 就等於「on」,否則為"off"
    %{HTTP_USER_AGENT}:User Agent
    %{REQUEST_FILENAME}:訪問的檔案名稱

實際案例(許願清單)

Old New
http://www.gwinstek.com/en-global/FaqSearch/faqs https://www.gwinstek.com/en-global/faq/index
http://www.gwinstek.com/en-global/Form/contact_us_form https://www.gwinstek.com/en-global/contact_us/index
http://www.gwinstek.com/en-global/Support/download https://www.gwinstek.com/en-global/download/index
http://www.gwinstek.com.tw/tw/index.aspx http://www.gwinstek.com
http://www.gwinstek.com.tw/tw/faq/faqquestionlist.aspx?bid=106 https://www.gwinstek.com/en-global/faq/index?cate=105&subcate=248&ser=562&key=
http://www.gwinstek.com.tw/tw/salescontact.aspx https://www.gwinstek.com/en-global/contact_us/index
http://www.gwinstek.com.tw/tw/faq/faqquestionlist.aspx?bid=33 https://www.gwinstek.com/en-global/faq/index?cate=55&subcate=92&ser=82&key=

  目錄