2011-05-04 192 views
1

我有一種情況,我需要將國家代碼添加到nginx中的所有請求中。如何在nginx中爲每個請求添加一個變量?

例如,如果用戶訪問http://example.com:3333/html/about,那麼我應該(使用nginx的重寫)重定向到http://example.com:3333/html/about?country_code=en

我有以下重寫,但我得到「太多的循環」。

rewrite ^(.*)$ http://$host:3333/$1?country_code=en last; 

我該如何解決?

nginx.conf

   server { 


### USA specific config ###                                          
if ($geoip_country_code = US) { 
    # do something here for USA visitors; 
    # root path /var/www/html/content/usa/;                                      
rewrite ^(.*)$ http://$host:3333/$1?country_code=en last; 

} 


} 

回答

0

試試這個:

原:

rewrite ^(.*)$ http://$host:3333/$1?country_code=en 

新:

rewrite ^(.*)(?!\?country_code=[a-z][a-z])$ http://$host:3333/$1?country_code=en 

我認爲nginx的支持使用共同排除模式斷言mmon (?!...)語法。負面超前說明,當網址末尾的?country_code=nn不是時,匹配(和重寫)應該發生。 (如果它在URL的中間,這個重寫仍然會發生。)

+0

//謝謝你的回覆。我可以在不檢查請求是否包含國家的情況下執行此操作嗎?如果我按照您的建議進行操作,用戶可以手動發送country_code來覆蓋country_code。 – Moon 2011-05-05 07:31:33

2
if ($geoip_country_code = US) { 
    set $test "US"; 
} 
if ($arg_country_code != 'en') { 
    set $test "{$test}_R"; 
} 
if ($test = 'US_R') { 
    rewrite ^(.*)$ http://$host:3333/$1?country_code=en last; 
} 
+0

@Timofey Stolbov //對不起,我忘了把我的帖子放在最後。我實際上有最後一個在我的原始代碼。 – Moon 2011-05-05 18:03:11

+0

@Moon,你可以顯示整個服務器{}配置嗎? – 2011-05-05 18:31:14

+0

@Timofey Stolbov //編輯! – Moon 2011-05-05 18:36:07