Sunday, November 1, 2015

How rewrite a URI in nginx?



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.


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 =    (longest match wins)
location ^~ (longest match wins)
location ~ (first defined match wins)
location (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!


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...