Search code examples
restconfigurationurl-rewritingnginxstatic-files

Nginx url rewrite for restful url


I have a Rails web app which has static files under dynamic restful urls. For example:

/projects/1/attachments/some_file.xls

I want to setup Nginx to redirect to the static file on the server:

/public/attachments/1/some_file.xls

Where 1 is the dynamic project id.

How would the location block and rewrite statement look for the Nginx config file?


UPDATE

I marked an answer below as it answers my original question. Though rewriting my project attachment urls wasn't necessary in my case. I forgot that I was already remapping the url in my Rails view erb.

My true goal was to stop Thin from adding caching response headers to my attachment files. Ultimately, I was able to prevent this with Nginx by just adding a location for attachments like such:

location /attachments/ {
    expires    off;
    add_header Pragma "no-cache";
    add_header Cache-Control "no-cache, no-store";
    access_log off; 
    break;
}

Solution

  • Here is simple example.

    location /project/ {
        rewrite ^/project/([0-9]+)/attachments/(.*)$ /public/attachments/$1/$2 last;
    }
    

    If you want more complicated rule, see the official help.

    http://wiki.nginx.org/HttpRewriteModule#rewrite