如何在 nginx 中重写 URI?

ama*_*nda 2 rewrite nginx

请考虑我的根目录中的以下目录结构:

/resources/css
/resources/js
/resources/templates
/resources/images
Run Code Online (Sandbox Code Playgroud)

我想提供来自上述目录的静态内容,但我也想允许像这样的重写工作:

rewrite ^/([a-z]+)(.*)$    /index.php?p1=$1&p2=$2;
Run Code Online (Sandbox Code Playgroud)

例如myurl.com/register/...重写为myurl.com/index.php?p1=register&p2=...

但该规则也会重写/resources/,那么我如何/resources从重写中排除呢?或者我需要再次重写吗?我尝试过的一切似乎都不起作用,所以显然我不明白一些事情。

ama*_*nda 5

下面的配置是我发现有效的,因为位置语句的优先级相同,它们按顺序检查。

这帮助我理解了位置块的优先级:

location =  <path>  (longest match wins)
location ^~ <path>  (longest match wins)
location ~  <path>  (first defined match wins)
location    <path>  (longest match wins)
Run Code Online (Sandbox Code Playgroud)

这是配置:

// match all css/js/images in resource path

location ~ ^/resources {
        root   /mypath/myurl.com;
        try_files $uri =404;
        break;
}

// allow myurl.com/register etc:

location ~  ^/([a-z]+)/(.*)$ {
        root   /mypath/myurl.com;
        rewrite ^/([a-z]+)(.*)$    /index.php?p1=$1&p2=$2;
}

// everything else:

location ~ / {
    root   /mypath/myurl.com;
    index  index.php;
}
Run Code Online (Sandbox Code Playgroud)

欢迎评论!