iT邦幫忙

1

Apache rewrite問題

  • 分享至 

  • xImage

各位大大好,
小弟最近在架設Apache server 遇到了幾個有關mod_rewrite 的問題,
但由於小弟還是新手觀念非常薄弱,所以希望在此有大大可以為小弟解惑。

小弟的目標是正確來說應該是能夠輸入以下URL
http://localhost/index.php?name=test&id=1234
然後會自動跳轉到
http://localhost/test/1234

所以目前小弟有一段轉址設定必須加入apache 設定中(以下為小弟的.htaccess檔 已確認此檔案可以正常運行):
RewriteEngine on
RewriteBase /
RewriteRule ^([0-9a-z]+)/([0-9]*)$ index.php?name=$1&id=$2

但是試了好久還是會一直出現The requested URL was not found on this server.
http://localhost/index.php?name=test&id=1234
請問哪個部分有錯?弄好久搞不定 ... ?
謝謝。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
wiseguy
iT邦超人 1 級 ‧ 2022-11-21 23:50:52

不太理解你的『已確認此檔案可以正常運行』是怎麼確認的?重跑 apache 沒有錯誤訊息嗎?
那個 RewriteRule 雖然 RegExp 沒問題,但是跟你的原始 URL 不吻合啊,所以不會跑這個 Rule,當然也就 URL not found。
RewriteRule 改成這樣,前面多加一個 /

RewriteRule ^/([0-9a-z]+)/([0-9]*)$ /index.php?name=$1&id=$2
看更多先前的回應...收起先前的回應...
s2266888 iT邦新手 5 級 ‧ 2022-11-22 13:24:39 檢舉

『已確認此檔案可以正常運行』
=>這個意思是指已試過簡單的範例確保.htaccess檔案有生效

但是跟你的原始 URL 不吻合啊,所以不會跑這個 Rule,當然也就 URL not found。
=> 有點不太懂這個意思

容我更正一下
小弟的目標是正確來說應該是能夠輸入以下URL
http://localhost/index.php?name=test&id=1234
然後會自動跳轉到
http://localhost/test/1234

以下是調整過後的.htaccess
RewriteEngine on
RewriteBase /
RewriteRule ^/([0-9a-z]+)/([0-9]*)$ /index.php?name=$1&id=$2

但是輸入以下url還是一樣會顯示error The requested URL was not found on this server.
http://localhost/index.php?name=test&id=1234

請問哪個部分有出錯?或者是其實根本不應該這樣RewriteRule.. ?
謝謝。

wiseguy iT邦超人 1 級 ‧ 2022-11-22 19:52:10 檢舉

輸入以下URL
http://localhost/index.php?name=test&id=1234
然後會自動跳轉到
http://localhost/test/1234

你的 rerwite 跟你所說的,剛好是顛倒耶!確定一下好嗎。
通常是輸入下面那個虛擬網址,然後真正在 server 端執行的是上面那個 index.php?name=test&id=1234。怎麼你的需求是顛倒的?那下方的虛擬網址要怎麼執行?

s2266888 iT邦新手 5 級 ‧ 2022-11-23 12:10:42 檢舉

簡單來說我實際的檔案index.php就是存在apache server的http://localhost/test/1234

但是今天我想用http://localhost/index.php?name=test&id=1234
的格式去下載index.php檔案

看來我的需求寫法應該是顛倒的,但如果依照我現在的需求要怎麼改寫呢?是不是就不能用RewriteRule 去做改寫規則了?

抱歉~因為小弟剛學對apache還很不熟,請大大多多包涵
謝謝

wiseguy iT邦超人 1 級 ‧ 2022-11-24 00:01:31 檢舉

照你所說的,你根本多此一舉,就直接開 /test/1234 目錄,把 index.php 放進去就是了,幹麻還需要 rewrite ?
不過我還是覺得你可能誤會什麼了。
一般會用 /test/1234 這種路徑法,來取代 ?name=test&id=1234 這種參數法。而不是你描述的相反。就因為參數法比較冗長不易記,又難看。這是化難為易,怎麼反而你是化易為難?

s2266888 iT邦新手 5 級 ‧ 2022-11-24 10:43:03 檢舉

因為 ?name=test&id=1234 這種參數法主要是為了要模擬客戶的環境,客戶就是用如此格式去下載檔案的~

我要發表回答

立即登入回答