Nginx – How rewrite a URI in nginx

nginxrewrite

Please consider the following directory structure in my root:

/resources/css
/resources/js
/resources/templates
/resources/images

I want to serve static content from the above directories but
I also want to allow a rewrite like this to work:

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

For example myurl.com/register/... is rewritten to myurl.com/index.php?p1=register&p2=...

But that rule also rewrites /resources/, so how do I exclude /resources from the rewrite? Or do I need another rewrite? Nothing I've tried seems to work so obviously I'm not understanding something.

Best Answer

The config below is what I found that works, since the location statements are all the same precedence they are checked in order.

This helped me understand the precedence of location blocks:

location =  <path>  (longest match wins)
location ^~ <path>  (longest match wins)
location ~  <path>  (first defined match wins)
location    <path>  (longest match wins)

Here is the config:

// 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;
}

Comments welcome!