0

I'm running a web application at my site's root. I would like it so that all subdirectories (even ones that exist) are directed to the root e.g. example.com/anything would redirect to example.com.

Gmail does this - if I'm viewing my inbox at:

https://mail.google.com/mail/#inbox

And I attempt to go to:

https://mail.google.com/mail/#inbox/some-other-place

I am just sent back to https://mail.google.com/mail/#inbox, rather than being presented with an error page.

How can I accomplish this in nginx?

If I just stick return 301... inside the root location block, I end up with a redirect loop. I tried also using try_files like this:

location / {
    try_files $uri $uri/ @home;
}

location @home {
    return 301 example.com;
}

This works for non-existent files or directories, however, nginx will still serve subdirectories and files if they do exist.

Thanks.

0

Anything after the hashtag is not sent to the server by the browser, it is processed by the JS code in the browser.

If you want to do that with real paths, not with hashtags, you have to make 2 locations:

location / {
    root ...;
    # no redirect
}

location ~ ^/.+$ {
    try_files
}

This will avoid the redirect loop.

  • The problem is, if I put try_files under the second block there, it will match existing files, so they won't get redirected (like my example in my question). ALSO, one thing I forgot to mention is that the app is a php app. I'm using php-fpm so php files need to still be passed to FastCGI (i.e. not redirected to the root). – Ellis Apr 15 '14 at 15:16
  • Also, putting the return line in the second location block causes a redirect loop. I'm not sure why, because I thought that regex would match one or more characters after the '/'. – Ellis Apr 15 '14 at 15:27

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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