nginx location redirect to folder with name as requested domain

Tomas Prado asked:

I’m new to nginx and I want to do this:

If the URL contains "/assets" redirect to "/communities/$url_domain"

In other words:

Requested: "http://www.cats.com/assets/superfile.png"
Redirected:"http://www.cats.com/communities/cats.com/superfile.png"

It’s something super simple but it’s not working.

What I have done

location /assets {
    root /communities/$host;
}

But whenever I try to access a file from /assets I get a

404 Not Found

nginx/1.8.1

What I’m doing wrong?
Thanks!

EDIT:

OK.
I activated logs and saw this:

2016/02/10 17:27:16 [error] 31#0: *1 open() "/communities/www.cats.com/assets/superfile.png" failed (2: No such file or directory), client: 192.168.1.254, server: _, request: "GET /assets/superfile.png HTTP/1.1", host: "www.cats.com"

I’ll investigate more If I can extract the domain part of the url

EDIT2:
Directory structure

/
--/communities/
--------------/cats.com/
---------------------superfile.png

Users will request this URL
www.cats.com/assets/superfile.png

And they will see the same URL. Im trying that nginx internally look for:
www.cats.com/communities/cats.com/superfile.png

My answer:


You need to use an alias instead:

location /assets/ {
    alias /communities/$host/;
}

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.