2011-03-23 189 views
0

有人可以幫我做我的nginx重寫規則。我有這樣的問題重寫規則nginx

如果在www.abc.com/name_dir/*找不到文件,它將重定向到www.abc.com/name_dir/index.php。

例如: 找不到www.abc.com/xxx/*重定向到www.abc.com/xxx/index.php 找不到www.abc.com/yyy/*重定向到www。 abc.com/yyy/index.php 找不到www.abc.com/zzz/*重定向到www.abc.com/zzz/index.php 找不到www.abc.com/kk/*重定向到www.abc.com/kkk/index.php ... 我有一千個name_dir的問題。我有這樣的nginx.conf

if (-f $request_filename) { 
     break; 
    } 
    if (-d $request_filename) { 
     rewrite (^.+$) $1/ 
     break; 
    } 
    if (!-e $request_filename) { 
     rewrite ^/xxx/(.*)$ /xxx/index.php?$1 last; 
     rewrite ^.+?(/.*\.php)$ $1 last; 
    } 

在配置上面只有重定向name_dir xxx。如何重寫規則以重定向所有目錄? 感謝您的幫助

回答

2

你想在這裏使用try_files到check for the existence of files而不是if語句(因爲If在Nginx中是Evil)。

要到一個單獨的目錄,它會像:

location /xxx/{ 
    try_files $uri $uri/ /xxx/index.php; 
    index index.php 
} 

這樣做是嘗試的URI作爲文件第一。如果這不起作用,它會嘗試作爲一個目錄。如果兩者都不起作用,它將默認爲/ xxx /的index.php。額外的指標線,以防止它顯示,如果你直接去whatever.com/xxx

使用正則表達式空白頁,我們可以擴展這個規則有多個目錄工作:

location ~* ^(/.*)/{ 
    try_files $uri $uri/ $1/index.php?$uri&$args; 
    index index.php 
} 

這應該抓住完整的目錄結構並將其路由到適當的索引。

  • abc.com/yyy/nonexistant.php ==> abc.com/yyy/index.php
  • abc.com/yyy/zzz/nonexistant.php ==> abc.com/yyy/ ZZZ/index.php文件

如果你只是想第二個例子去YYY/index.php文件,相反在位置使用這個表達式:

^(/.*?)/