2014-04-27 31 views
1

需要使用標誌RewriteCondmod_rewrite已啓用並正在運行,我的問題是如何表達我的需求:有一條通用規則和一些例外規則,例外情況不起作用,並且解決方案必須避免循環。如何在通用正則表達式規則的例外中避免循環?

/var/www前使用mod_rewrite的,與通常的文件夾那樣工作/var/www/wiki/var/www/foo/var/www/bar(每個都有其索引)。我需要保持這種行爲。現在

,與mod_rewrite的,我使用的是/var/www/index.php重定向一些特殊的字符串,那場比賽^([a-z0-9]+),如http://myDomain/foo123http://myDomain/wiikii。但它也匹配「wiki」和「foo」,即需要異常處理


/var/www/.htaccess

RewriteEngine on 
RewriteRule ^/?(foo|bar)([0-9]+)  index.php?$1=$2 
RewriteRule ^/?([a-z0-9]+)   index.php?foobar=$1 

所以,像http://myDomain/wiki是重定向到index.php?foobar=wiki但我需要它,沒有重定向,需要Apache將/wiki。 PS:我嘗試了一些變化,並將index.php(使用內部重定向)進行了一些更改,但需要雅緻而安全的Apache Rewrite解決方案,以避免出現循環

回答

1

通常條件是要走的路,覈對REQUEST_URI。

RewriteCond %{REQUEST_URI} !^/(wiki|foo)$ <-- added 
RewriteRule ^([a-z0-9]+)$   index.php?foobar=$1 [L] 

另一種方法是使用例如,在你的正則表達式中的負向前瞻。例如:

RewriteRule ^(?!(?:foo|wiki)$)([a-z0-9]+) ... 

但我發現任何零個寬度斷言是相當複雜的/脆弱/不直觀,即使正常的正則表達式來很容易給你。

?!是負面的前瞻 ?:只是沒有捕獲parens的「或」

關於這些最令人困惑的部分是,pcre努力找到一種方式來不滿足負面看法,換句話說,它努力嘗試有一個成功的整體比賽。

+0

謝謝! (確定不使用「替代」直覺解決方案)那麼現在我必須理解和比較(性能?)和Justin的解決方案:1)RewriteCond保護RewriteRule,因此像「wiki」這樣的異常不由RewriteRule處理; 2)Apache有一個「默認行爲」,所以「wiki」由這個默認值處理。是嗎??關於表現,你和Justin的解決方案有什麼不同? –

1

如果你不想爲wiki文件夾(及其他)任何重定向,您可以添加一個條件

RewriteEngine on 

# If requested url is an existing file or folder, don't touch it 
RewriteCond %{REQUEST_FILENAME} -d [OR] 
RewriteCond %{REQUEST_FILENAME} -f 
RewriteRule . - [L] 

# If we reach here, this means it's not a file or folder, we can rewrite... 
RewriteRule ^(foo|bar)([0-9]+)$  index.php?$1=$2 [L] 
RewriteRule ^([a-z0-9]+)$   index.php?foobar=$1 [L] 

此外,您還可以使用排序例外代替,如果你不想它是應用在所有文件夾/文件

RewriteEngine on 

# If requested url is a folder/file in exception list, don't touch it 
RewriteCond %{REQUEST_URI} ^/(foo|bar|example_file\.html|wiki)$ 
RewriteRule . - [L] 

# If we reach here, this means it's not a file or folder in exception list, we can rewrite... 
RewriteRule ^(foo|bar)([0-9]+)$  index.php?$1=$2 [L] 
RewriteRule ^([a-z0-9]+)$   index.php?foobar=$1 [L]