4

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?

shgnInc
  • 2,054
  • 1
  • 23
  • 34
Ranknoodle
  • 847
  • 12
  • 28

3 Answers3

3

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;
    }
  }
}
Ranknoodle
  • 847
  • 12
  • 28
2

Make it simple.

location / {
    rewrite ^ http://example.com;
}

location = / {
}
Alexey Ten
  • 13,794
  • 6
  • 44
  • 54
  • I have an older version of nginx nginx version: nginx/0.5.35 built by gcc 4.1.2 20070626 (Red Hat 4.1.2-14) configure arguments: --sbin-path=/usr/local/sbin --with-http_ssl_module so the return directive was throwing an error so I tried this and still get a redirection loop: location / { rewrite ^ http://www.example.com; } – Ranknoodle Mar 17 '14 at 21:55
  • Changed answer to conform 0.5 – Alexey Ten Mar 17 '14 at 22:09
  • Changed and it still has redirect loop BUT it does redirect all other request to the root url which is good. I think what is needed is something like if (location not root "/" {rewrite ^ http://example.com;} – Ranknoodle Mar 17 '14 at 22:31
  • Thanks for this - ended up finding this just after asking the question myself over in StackFault.... http://serverfault.com/q/734838/86531 – Nick Nov 08 '15 at 22:19
  • @user1394013 no, it’s not, unless you’ve made mistakes – Alexey Ten Feb 24 '20 at 14:35
1

The below is a more modern syntax for trying various file resources for existence, with progressive defaults.

Be sure to uncomment other location paths underneath the one below, to avoid more specific matches, if necessary.

Also, if is evil when used in location context.

server {
    listen 1.2.3.4:80;
    server_name example.com;
    
    root /path/to/document/root;

    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}
ib.
  • 27,830
  • 11
  • 80
  • 100
zoot
  • 304
  • 2
  • 7