Apache 的 mod_userdir
我們公司提供服務來使用 Apache 的“每用戶目錄模式”托管我們的網頁(請參閱doc)。
即 Alice、Bob 和我自己可以通過
- http://example.com/~alice
- http://example.com/~bob
- http://example.com/~me
分別。
問題
問題是我在基于根的結構上開發了我的網站。
即在dev 環境中,可以通過http://example.com/resource訪問資源,在prod 環境中應該翻譯為http://example.com/~me/resource。
出于顯而易見的原因,這種結構更可取,因為它更容易遷移到另一個 Web 服務器或將代碼移植到其他除錯環境(例如:IIS、Wampserver,...)。我最初的計劃是以這種方式撰寫我的代碼,然后在 .htaccess 中重定向流量。
通過 .htaccess 重定向
我已經嘗試了這里列出的所有解決方案,但沒有任何成功。
我認為上述鏈接中提出的解決方案與我的問題不同,因為.htaccess它位于root,并且重定向是從root 到 subfolder完成的。
就我而言, .htaccess 位于subfolder中。單擊 URL 時,它將客戶端重定向到http://example.com/resource,這是對root的請求。此時,我無法使用 my 重定向流量,.htaccess因為客戶端現在不在我的子目錄中。
這是我用我的.htaccess.
解決方案 1(重定向匹配):
RedirectMatch ^/$ /~me/
結果:http ://example.com/~me被無限重定向到http://example.com/~me/~me/~me/~me/~me/~me/~me/~me/~me /~me/~me/~me/~me/~me/~me/~me/~me。
解決方案 2(重寫規則):
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/~me/
RewriteRule ^(.*)$ /~me/$1
結果:未執行重定向。可能是因為我的 .htaccess 變得無效。
題
Is there a way to redirect traffic to my subdirectory using my own .htaccess?
A very inelegant way is to redirect traffic from root, but this can disrupt traffic to Alice, Bob, and the admin.
Say, in the .htaccess of the root, all traffic from http://example.com/resource will be redirected to http://example.com/~me/resource. But if Alice, Bob, or the admin uses http://example.com/resource, they will be unhappy with my rule.
Is there any solution to this?
Edit: As pertinently pointed out by Stephen Ostermiller, one idea is to enforce redirection by setting up the base URL as per my environment. However, I'm asking if there would be any solution that does not involve rewriting my code and re-debugging all URL redirections. For example, by tweaking .htaccess or any superglobal config file would do.
uj5u.com熱心網友回復:
感謝斯蒂芬奧斯特米勒的評論,我在這里總結一下作為我問題的答案。
我們通常不想依賴重定向來糾正我們網路應用程式中的鏈接。最小化重定向更不容易出錯,性能更好,并且有更好的SEO鏈接到實際 URL。
我所做的是使用 .htaccess 中的 SetEnv 定義一個環境變數來指定基本 URL。如果沒有定義,那么它會在我的 PHP 代碼中回傳 false,但一切都應該正常作業(您可以將布林值與字串連接起來)。否則,如果指定了環境變數,我的所有 URL 都會用基本 URL 替換根。
正如 Stephen Ostermiller 建議的那樣,如果需要將其部署到子目錄,建議為您的 web 應用程式設定一個基本 URL 的配置選項。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456039.html
標籤:apache .htaccess redirect mod-rewrite mod-userdir
