2014-09-04 85 views
0

我嘗試將我的服務器從Apache移至基於Nginx的設置。但是,我遇到了一些問題,讓我的htaccess Apache魔術的一部分在Nginx中工作。Nginx,重寫多個子文件夾

的代碼的.htaccess我想轉讓是:

RewriteRule ^([a-zA-Z0-9_]+)/$     /index.php?page=$1 [L,QSA] 
RewriteRule ^([a-zA-Z0-9_]+).html$    /index.php?page=$1 [L,QSA] 
RewriteRule ^([a-zA-Z0-9_]+)/([0-9]+)/.*/([a-zA-Z0-9_]+)$  /index.php?page=$1&id=$2&sub=$3 [L,QSA] 
RewriteRule ^([a-zA-Z0-9_]+)/([0-9]+)/.*$  /index.php?page=$1&id=$2 [L,QSA] 

我用了一個online converter這給了我以下位置塊:

location/{ 
rewrite ^/([a-zA-Z0-9_]+)/$ /index.php?page=$1 break; 
rewrite ^/([a-zA-Z0-9_]+).html$ /index.php?page=$1 break; 
rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*/([a-zA-Z0-9_]+)$ /index.php?page=$1&id=$2&sub=$3 break; 
rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*$ /index.php?page=$1&id=$2 break; 
} 

可悲的是,我只能夠得到一次重寫的位置(我放在後面的那個位置)。我似乎無法將多個子文件夾URL動態重寫爲單個PHP腳本的參數。

任何幫助? Nginx做這種重寫的方式是什麼?我試着用不同子文件夾的幾個位置,但我寧願有一個通用的解決方案,無論工作的URL是什麼都不管用。

回答

2

使用爲每個規則的不同位置塊:

location ~ ^/[a-zA-Z0-9_]+/$ { 
    rewrite ^/([a-zA-Z0-9_]+)/$ /index.php?page=$1 last; 
} 

location ~ ^/[a-zA-Z0-9_]+.html$ { 
    rewrite ^/([a-zA-Z0-9_]+).html$ /index.php?page=$1 last; 
} 

location ~ ^/[a-zA-Z0-9_]+/[0-9]+/.*/[a-zA-Z0-9_]+$ { 
    rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*/([a-zA-Z0-9_]+)$ /index.php?page=$1&id=$2&sub=$3 last; 
} 

location ~ ^/[a-zA-Z0-9_]+/[0-9]+/.*$ { 
    rewrite ^/([a-zA-Z0-9_]+)/([0-9]+)/.*$ /index.php?page=$1&id=$2 last; 
} 

location = /index.php { 
    # your proxy rules here... 
} 

重寫規則以上使用最後選項,這是在nginx docs解釋:

last 
    stops processing the current set of ngx_http_rewrite_module 
    directives and starts a search for a new location matching the 
    changed URI; 
+0

就像一個魅力, 謝謝!我沒有嘗試在位置線中使用正則表達式。 – Sander 2014-09-08 09:06:35

相關問題