盡管嵌套在任意數量的子目錄中,但我有以下目錄結構/root作為我的根目錄:
- example.com/dir1/root
- 客戶端/構建
- api
當用戶導航到 時example.com/dir1/root/,我希望將所有請求重定向到example.com/dir1/root/client/build/但不更改 URL,就好像build/目錄內容在里面一樣root/。
此外,我希望所有請求example.com/dir1/root/api/*都被重定向到example.com/dir1/root/api/. 同樣,無需更改 URL。
這是我目前的嘗試,因為我對 .htaccess 的作業原理知之甚少:
RewriteEngine on
# If an existing asset or directory is requested go to it as it is.
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# Redirect all requests under /api/ to the API.
RewriteCond %{REQUEST_URI} ^/api/
RewriteRule ^ api/index.php [L]
# If the requested resource doesn't exist, use index.html (html5mode)
RewriteRule ^ client/build/index.html [L]
注意:我已經搜索但沒有找到任何針對此特定場景的答案,并且鑒于我對 htaccess 的了解不足,我無法很好地將現有答案拼湊在一起。
uj5u.com熱心網友回復:
index.html正在請求資源,例如example.com/dir1/root/assets/style.cssthis 駐留在/root/client/build/assets/. 本質上,我想/root/表現得好像它實際上是/root/client/build,除非在實體/root/api/中被請求。
我會將其實作為 2 個單獨的.htaccess檔案。“根”目錄中的一個(即。/dir1/root/.htaccess)處理“api”請求并將其他所有內容重寫為client/build(即“假根”)。其中的另一個.htaccess檔案/dir1/root/client/build/.htaccess僅處理您的應用程式前端中的路由。
例如:
# /dir1/root/.htaccess
RewriteEngine On
# Rewrite all requests under /api/ to the API handler "index.php"
RewriteRule ^api/(?!index\.php) api/index.php [L]
# Rewrite everything else to the "client/build/" subdirectory
RewriteRule (.*) client/build/$1 [L]
和...
# /dir1/root/client/build/.htaccess
DirectoryIndex index.html
RewriteEngine On
# Front-controller
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html [L]
子目錄中檔案(包含 mod_rewrite 指令)的存在.htaccess也可以防止重寫回圈,因為它可以防止.htaccess重新處理父目錄中的指令(并client/build/...一次又一次地重寫請求)。
快速瀏覽您現有的規則...
# If an existing asset or directory is requested go to it as it is. RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] # Redirect all requests under /api/ to the API. RewriteCond %{REQUEST_URI} ^/api/ RewriteRule ^ api/index.php [L] # If the requested resource doesn't exist, use index.html (html5mode) RewriteRule ^ client/build/index.html [L]
您現有規則的問題:
由于第一條規則阻止映射到正在處理的檔案或目錄的任何請求,因此它還將阻止對
/dir1/root/自身(即目錄)的請求被重寫為/dir1/root/client/build/index.html.該條件
RewriteCond %{REQUEST_URI} ^/api/永遠不會成功,因為REQUEST_URI服務器變數包含相對于根的 URL 路徑,即。/dir1/root/api/.由于其他所有內容都從“根”重寫為
client/build/index.html,因此也存在于其中的靜態資產client/build/未正確重寫(它們被重寫為index.html可能導致意外回應)。您無法在“根”檔案中執行檔案系統檢查,因為在重寫后僅與“存在”
.htaccess相關的靜態資產。index.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/459220.html
