2014-09-04 86 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

相关问题