![](/img/trans.png)
[英]correct Apache RewriteCond and RewriteRule when using RewriteMap?
[英]Apache RewriteRule with RewriteMap
我有一個看起來像這樣的RewriteMap
:
Guide 1
Mini-Guide 2
White Paper 3
我將它包含在Apache
RewriteMap legacy txt:/var/www/site/var/rewrite_map.txt
我想創建一個RewriteRule
,它只允許來自所述RewriteMap
左側的值處於這個位置;
RewriteRule ^/section/downloads/(${legacy})/(.*)$ /blah.php?subsection=${legacy:%1}&title=$2
我知道我可以在右側使用${legacy}
,但我可以在左側使用它,如果是這樣,怎么樣?
在地圖文件中,左側是鍵,右側是值。 創建匹配地圖的規則時,輸入密鑰並輸出值。
將您的RewriteRule更改為:
# Put these on one line
RewriteRule ^/section/downloads/([a-zA-Z-]+)/(.*)$
/blah.php?subsection=${legacy:$1}&title=$2
第一個分組捕獲傳入URL中的字符串。 替換中的$ 1將其應用於指定的地圖。 要設置默認值,請將${legacy:$1}
更改${legacy:$1|Unknown}
。
最后,如果您只希望規則處理映射文件中的值,請添加RewriteCond
:
RewriteCond ${legacy:$1|Unknown} !Unknown
# Put these on one line
RewriteRule ^/section/downloads/([a-zA-Z-]+)/(.*)$
/blah.php?subsection=${legacy:$1}&title=$2
條件是,如果地圖未返回默認值( Unknown
),則運行下一個規則。 否則,跳過規則並繼續。
另一個變種:
# %1 will be the subpattern number1 afterwards
RewriteCond %{REQUEST_URI} ^/section/downloads/(.*)
# check if there is no mapping for %1
RewriteCond ${legacy:%1} !^$
# if there is rewrite it
RewriteRule ^/(.*) /blah.php?subsection=${legacy:%1}&title=$2 [R]
你說過,你想只允許在地圖中找到的值。 除非您在捕獲組的regex中指定其他限制,否則這是不可能的。 地圖本身無法做到這一點。 據我所知,沒有“map.keys”語法可以在左側應用模式。
但,
如果未找到捕獲的值,則可以指定默認值。 這條路:
## all on one line
RewriteRule ^/section/downloads/([a-zA-Z-]+)/(.*)$
/blah.php?subsection=${legacy:$1|defaultValue}&title=$2
用你喜歡的任何東西替換“defaultValue”。 例如,如果在地圖中找不到給定的arg,則為0(零)或“未發現”。
然后,您可以使用其他規則重寫該結果,或者只是允許它流過,並在URL處使用默認值提供“404”消息。
如果您選擇使用其他規則,那么它將如下所示:
## all on one line
RewriteRule ^/section/downloads/([a-zA-Z-]+)/(.*)$
/blah.php?subsection=${legacy:$1|notFoundMarker}&title=$2
## This rule fires if the lookupKey was not found in the map in the prior rule.
RewriteRule ^/blah.php?subsection=notFoundMarker /404.php [L]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.