我的.htaccess檔案中有以下內容。
RewriteEngine On
RewriteRule ^([^/] )?$ /member/profile.php?user=$1 [L]
RewriteRule ^assets(/.*)?$ /member/assets$1 [L]
RewriteRule ^images(/.*)?$ /member/images$1 [L]
RewriteRule ^php(/.*)?$ /member/php$1 [L]
想要的效果是:
https://example.com/username -> https://example.com/member/profile.php?user=$1
這行得通,但是,問題是由此發生了 2 個不希望的結果。
第一: https://example.com并https://example.com/回傳 404 錯誤,但https://example.com/index.php作業得很好。
第二: https://example.com/username/最終轉發https://example/member/php/?user=username并回傳 404 錯誤。
我也嘗試過
DirectoryIndex index.htm index.html index.php
但這似乎對這個問題沒有影響
我實際想要的最終結果看起來更像:
https://example.com -> https://example.com/index.php
https://example.com/ -> https://example.com/index.php
https://example.com/username -> https://example.com/member/profile.php?user=$1
https://example.com/username/ -> https://example.com/member/profile.php?user=$1
uj5u.com熱心網友回復:
RewriteRule ^([^/] )?$ /member/profile.php?user=$1 [L]
第一:
https://example.com并https://example.com/回傳 404 錯誤,但https://domain.name/index.php作業得很好。
第一條規則將捕獲請求(因為它允許空 URL 路徑)并將請求重寫為/member/profile.php?user=. 那么,大概是您的腳本觸發了 404?
實際上,看起來您之前缺少一個斜杠?來匹配可選的尾隨斜杠(即。/username或/username/),而不是使整個模式可選!IE。^([^/] )/?$
您還需要NS( nosubreq) 標志來防止 mod_dir 對DirectoryIndex(ie. index.php) 的子請求也被此規則捕獲。但是,這個規則可以說匹配太多了,因為它也會捕獲對index.php(以及您可能在根目錄中的任何其他檔案)的直接請求。那么,也許您需要對用戶名中允許的字符進行更多限制?^([^/.] )/?$例如,至少用?排除點(以及斜線)或者只允許字母和數字(和下劃線),例如。^(\w )/?$. (\w是一個簡寫字符類,表示[0-9a-zA-Z_].)
請注意,第一條規則也將匹配assets, imagesand php- 所以這些是有效的用戶名。這是故意的嗎?您可以顛倒規則,這樣就不會發生這種情況,但您需要確保沒有與這些字串匹配的用戶名。
注意:https://example.com和https://example.com/請求完全一樣。(瀏覽器有效地在主機名后附加斜杠以發出有效的 HTTP 請求。請參閱 Webmasters 堆疊上的以下問題:在瀏覽器中單擊主頁 URL 時是否自動添加尾隨斜杠?)
第二:
https://example.com/username/最終轉發https://example.com/member/php/?user=username并回傳 404 錯誤。
我看不到發布的指令會如何發生這種情況。除非用戶名是“assets”、“images”或“php”,否則您的所有規則都不匹配/username/(帶有斜杠)——但這仍然不會導致所述的重寫?但是,這會導致 404,因為重寫 URL 時實際上并沒有發生任何事情!/username/
你的規則也許應該這樣寫:
RewriteEngine On
RewriteRule ^(\w )/?$ member/profile.php?user=$1 [L]
RewriteRule ^assets(/.*) member/assets$1 [L]
RewriteRule ^images(/.*) member/images$1 [L]
RewriteRule ^php(/.*) member/php$1 [L]
規則 2、3 和 4 中的捕獲子模式不是可選的,因此我洗掉了尾隨的?$.
我還洗掉了替換字串上的斜杠前綴,使其成為相對檔案路徑。
這也可以進一步“簡化”為:
RewriteEngine On
RewriteBase /member
RewriteRule ^(\w )/?$ profile.php?user=$1 [L]
RewriteRule ^((assets|images|php)/.*) $1 [L]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465396.html
上一篇:處理帶有尾隨逗號的多行json
