【问题标题】:Nginx, rewrite multiple subfoldersNginx,重写多个子文件夹
【发布时间】:2014-10-29 04:58:38
【问题描述】:

我尝试将我的服务器从 Apache 移至基于 Nginx 的设置。但是,让我的 htaccess Apache 魔法的一部分在 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 都可以工作。

【问题讨论】:

    标签: apache nginx rewrite


    【解决方案1】:

    为每个规则使用不同的位置块:

    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...
    }
    

    上面的 rewrite 规则使用 last 选项,在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;
    

    【讨论】:

    • 像魅力一样工作,谢谢!我没有尝试在定位行中使用正则表达式。
    猜你喜欢
    • 2023-03-20
    • 2016-08-16
    • 2013-07-22
    • 2023-03-09
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多