如果會導致 404,請嘗試重寫到不同的 URL

如果會導致 404,請嘗試重寫到不同的 URL

我有一個正在開發的本地 tomcat 伺服器,用於使用本地 IIS 實例作為代理。

我這樣做是因為部署伺服器是一個痛苦的過程,因為很多內容不是(我所描述的)獨立的。來自不同項目的內容本質上被複製到伺服器的根目錄。我不想處理設定的麻煩,因此在重寫模組的幫助下,我可以將 URL 重寫到大部分虛擬目錄。

例如,

/js/* -> /someproject/js/*
/css/* -> /someproject/css/*
/**/*.pdf -> /someotherproject/pdf/*

然而,在一些特殊情況下,該方案不起作用,特別是當目標目錄存在重疊時。在部署中,一些資源被放置在同一目錄中,因此沒有真正的方法來區分哪個是哪個。這些文件沒有嚴格的模式,都是混合體。

例如,

/someproject1/file1.txt -> /file1.txt
/someproject2/book2.doc -> /book2.doc

因此,給定一個 url /file1.txt,我不知道是否可以重寫為 go tosomeproject1someproject2。所以我想如果有某種層次結構來嘗試重寫哪些網址,我就可以讓它運作。因此,我可能會採用類似 的 url /file3.txt,重寫為第一個顯示有效的模式。

/someproject1/file3.txt     # if 404, try the next
/someproject2/file3.txt     # if 404, try the next
/someotherproject/file3.txt # if 404, try the next
/file3.txt                  # fallback

這是只能用URL重寫模組來表達的東西嗎?

答案1

我能夠讓這個工作。

第一個障礙是我沒有意識到並非所有條件匹配類型都在全域範圍內可用(這是我編寫規則的地方)。只有Pattern可用的。我必須將範圍更改為“分散式”範圍(每個站點的規則)才能存取IsFileIsDirectory匹配類型。

然後從那裡,我可以用某種層次結構寫出我的規則。首先重寫以匹配我想先嘗試的模式,然後如果它不能解析為文件,請將其重寫為下一個模式並重複。

<rule name="try in project/content" stopProcessing="false">
    <match url=".*" />
    <action type="Rewrite" url="project/content/{R:0}" />
</rule>
<rule name="verify project/content" stopProcessing="false">
    <match url="(project)/content(/.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Rewrite" url="{R:1}{R:2}" />
</rule>

在我的特定情況下,我想先嘗試特定的子目錄,然後嘗試父目錄(如果它們不存在)。但理論上我可以對任何一組路徑執行此操作,只要我知道要以什麼順序嘗試它們。


因此,對於我在問題中的範例,我將設定以下規則:

<rule name="try in someproject1" stopProcessing="false">
    <match url=".*" />
    <action type="Rewrite" url="someproject1/{R:0}" />
</rule>
<rule name="try in someproject2 otherwise" stopProcessing="false">
    <match url="someproject1/(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Rewrite" url="someproject2/{R:1}" />
</rule>
<rule name="try in someotherproject otherwise" stopProcessing="false">
    <match url="someproject2/(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Rewrite" url="someotherproject/{R:1}" />
</rule>
<rule name="fallback to root otherwise" stopProcessing="false">
    <match url="someotherproject/(.*)" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Rewrite" url="{R:1}" />
</rule>

相關內容