2013-08-07 47 views
0

我想告訴我的服務器下面的請求重定向:正確的正則表達式來避免infinte循環使用重寫規則重定向301

http://example.es 
http://example.es/ 
http://example.es/es 
http://example.es/es/ 
http://www.example.es 
http://www.example.es/ 
http://www.example.es/es 

此頁:

http://www.example.es/es/ 

爲了做到這一點我有以下在我的.htaccess

#RewriteEngine On # Turn on the rewriting engine 
RewriteBase/
RewriteCond %{HTTP_HOST} ^(\.?example\.es(/|/es|/es/)?|www\.?example\.es(/|/es)?)$ [NC] 
RewriteRule ^(.*)$ http://www.example.es/es/ [R=301,L] 

問題是,它會導致無限的重定向,因爲t他希望URL http://www.example.com/es/內也有HTTP_HOST字符串。事情是我無法找到準確的正則表達式來避免這個問題。

中的.htaccess的其餘部分則如下:

php_flag register_long_arrays on 
php_flag register_globals on 
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css javascript application/javascript 
ExpiresActive On 
ExpiresByType text/css "access plus 1 years" 
ExpiresByType image/png "access plus 1 years" 
ExpiresByType application/javascript "access plus 1 years" 

Header set Connection keep-alive 

幫助是非常非常感謝!

乾杯!

回答

1

AFAIK Apache的重寫使用PERL正則表達式,因此支持負向預測。您可以使用其中一個來避免將http://www.example.com/es/與自身匹配。嘗試:

^(\.?example\.com(/|/es|/es/)?|www\.?example\.com(/|/es(?!/))?)$

1

記住%{HTTP_HOST}僅在URL匹配的主機名。

這種替換代碼:

Options +FollowSymLinks -MultiViews 
# Turn mod_rewrite on 
RewriteEngine On 

RewriteCond %{HTTP_HOST} ^(www\.)?(example\.ws)$ [NC] 
RewriteRule (?!^es/)^(.*)$ http://www.%1/es/$1 [R=301,L,NC] 
+0

對不起!爲了有一個更好的例子,我使用了.com域名,但我的案例真的與.es聯繫在一起。我改變了原來的問題。在錯誤的例子中,除了www.example.com/es之外的其他所有請求都可以正常工作,並且在此服務器上找不到「請求的URL/es/es」的下面的消息重定向到404頁面。我想是因爲我的例子不正確。此外,我瞭解RewriteCond正則表達式,但對RewriteRule沒有任何線索。爲什麼兩個^? ^是爲字符串的開頭,對吧? – Julen

+1

這實際上是一個負面的前瞻,這意味着執行RewriteRule所有的URL,除了當URL開始'/ es /' – anubhava

+1

我做了一個小的編輯,以適應你的最新的例子。現在就試試。 – anubhava

0

我得到的答案是這樣的:

Options +FollowSymLinks -MultiViews 
RewriteEngine On # Turn on the rewriting engine 
RewriteCond %{HTTP_HOST} ^(www\.)?(example\.es)$ [NC] 
RewriteRule ^(/|/es|/es/)?$ http://www.example.es/es/$1 [R=301,L,NC] 

感謝大家的幫助!