Nginx – forcing nginx to redirect to server root

nginxredirectrewrite

I have the following line in nginx:

try_files $uri $uri/ /index.html;

As far as I understand, it rewrites all queries to files that are not found to index.html.
Meaning, that index.html?foo=bar and idontexist.html?foo=bar leave the same result which screws up Google crawling.

How can I not rewrite but redirect to the default url?

The perfect solution would be even without the index.html.
So http://domain.com/idontexist.html?foo=bar would redirect using 301 to http://domain.com/?foo=bar

Best Answer

location / {
    try_files $uri $uri/ @to_home;
    ...
}

location @to_home {
    return 301 /$is_args$args;
}