nginxhttp-redirectdocument-root

Nginx 301 Redirect all non home page urls to home page


I'm shutting down a site and I need to 301 redirect all pages to the home page where I have a message saying that the site is being closed down.

Basically any http://example.com/anyfolder -> 301 to http://www.example.com

I have the following but this results in a redirection loop.

location ~ ^/([A-z]+) { rewrite ^ / permanent; }

What is the proper way to do this in nginx?


Solution

  • This worked for me. This is assuming you only have a index.html,htm and the other urls are missing the physical file on disk.

    server {
      listen      80;
      server_name www.example.com example.com;
      root /u/apps/example/www;
      index index.html;
    
      location / {
        if (!-e $request_filename) {
          rewrite ^ / permanent;
        }
      }
    }