根據HTTP_HOST重寫URL

根據HTTP_HOST重寫URL

基本上我希望用戶可以透過內部網路和網路存取該頁面。

若使用者透過內網存取該頁面,可在瀏覽器網址列輸入伺服器的內網IP即可192.168.x.x

但是當使用者透過網路存取該頁面時,他們可以輸入伺服器的公共IP,我會將URL重寫為伺服器的公共IP。

我已經嘗試過這個,但我得到了頁面未正確重定向

RewriteEngine   On
RewriteBase     /mypath/
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteCond     %{HTTP_HOST}        !192.168.0.1
RewriteRule     ^(.*)$          http://<public.ip.of.server>/mypath/$1/ [L,R=301]
RewriteCond     %{HTTP_HOST}        !<public.ip.of.server>
RewriteRule     ^(.*)$          http://192.168.0.1/mypath/$1/   [L,R=301]

我也嘗試過這個,但我得到了頁面500內部伺服器錯誤

<If "%{HTTP_HOST} == '192.168.0.1'">
RewriteEngine   On
RewriteBase     /mypath/
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://192.168.0.1/mypath/$1/   [L,R=301]
</If>
<If "%{HTTP_HOST} == 'public.ip.of.server'">
RewriteEngine   On
RewriteBase     /mypath/
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://<public.ip.of.server>/mypath/$1/ [L,R=301]
</If>

難道我做錯了什麼?

答案1

我正在使用 Apache 2.2.3

<If>指令是 Apache 2.4 核心的一部分。如果將這些指令放入 2.2 中,它們將導致 500 伺服器錯誤。根本不清楚您要做什麼,但您可以用<If>簡單的RewriteCond.

這裡重要的概念RewriteCond僅適用於緊隨其後的 RewriteRule指令,它們不適用於任何其他指令,僅適用於該指令。因此,如果您需要將條件套用到多個規則,則需要複製條件。

RewriteEngine   On
RewriteBase     /mypath/

RewriteCond     %{HTTP_HOST} ^192.168.0.1$
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://192.168.0.1/mypath/$1/   [L,R=301]

RewriteCond     %{HTTP_HOST} ^public.ip.of.server$
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$          http://<public.ip.of.server>/mypath/$1/ [L,R=301]

但你可以擺脫所有這些,因為你可以在不使用該http://hostname位的情況下重定向:

RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_URI}      !(.*)/$
RewriteCond     %{REQUEST_METHOD}   GET
RewriteRule     ^(.*)$  /mypath/$1/   [L,R=301]

這對於任何主機來說都可以實現上述目的。

相關內容