I need to setup nginx to rewrite URL's from example.com/page1/page2 to example.com/#page1/page2, in order to make backbone.js´s Routing work.

Basically it's all about the # that needs to be appended after the first slash in the URL to make it work.

But how do I do that? I can't really find any good example online.

The current nginx configuration:

location / {
    root   /var/www/frontend;
    try_files $uri $uri/ @rewrites;
}

location @rewrites {
    rewrite ^/~(.*)/(.*)/? /index.html#$1/$2 last;
}
link|improve this question

feedback

1 Answer

up vote 0 down vote accepted

Since fragment URLs are processed client side, you need to redirect the user with a 301/302. Try the 'permanent' flag

location / {
    root   /var/www/frontend;
    try_files $uri $uri/ @rewrites;
}

location @rewrites {
    rewrite ^/~(.*)/(.*)/? /#$1/$2 permanent;
}
link|improve this answer
Thanks but that unfortunately leads to 404's all over the place – Industrial Feb 8 at 10:30
@Industrial Does the URL show in the browser correctly? The URL shown should be /index.html#some/path – sam Feb 8 at 10:31
Yep. example.com/index.html#page/query leads to 404 as it is – Industrial Feb 8 at 10:36
1  
@Industrial Then it's a problem with your frontend code, the rewrite is doing what you're asking it do do. If you take off the index.html bit and make the rewrite rewrite ^/~(.*)/(.*)/? /#$1/$2 permanent; the result will be exactly as you specified in your question – sam Feb 8 at 10:39
Oh. I tried that as well and same result. However using rewrite ^ /#$uri redirect; makes it work, but it appends double slashes to the final url. Any ideas? – Industrial Feb 8 at 10:42
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.