Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: Return 301 Redirect When 404 Error

What I want to do whenever I get a 404 error on my domain, automatically 301 to the homepage.

I have a lot of old blog posts and such that were linked to, but I don't have them on the blog and if anyone happens to click through from another site that they get kicked to the homepage.

How can I do this inside nginx?

 server {
        listen             12680;
        root       /home/noahc/webapps/nginx/html/noahc/;
        server_name    www.noahc.net, noahc.net;
        error_page 404 @foobar;

        location @foobar {
                rewrite  .*  / permanent;
                }
         }
like image 873
Noah Clark Avatar asked Feb 05 '12 08:02

Noah Clark


People also ask

Why is Nginx returning 301?

Temporary and Permanent Nginx Redirect Explained On the other hand, a permanent Nginx redirect informs the web browser that it should permanently link the old page or domain to a new location or domain. To map this change, the redirects response code 301 is used for designating the permanent movement of a page.

What is 404 not found nginx?

Essentially, the “404 error” indicates that your or your visitor's web browser was connected successfully to the website server or the host. However, it was unable to locate the requested resource, such as filename or any specific URL.


2 Answers

The error_page setting can do this for you already:

error_page 404 =301 http://example.com/;

like image 190
Jon Avatar answered Sep 18 '22 21:09

Jon


There's a faster way through it:

error_page 404 = @foobar;

location @foobar {
  return 301 /;
}

By "faster" I mean "no useless regexp matching inside web server" by using return instead of rewrite.

like image 41
kworr Avatar answered Sep 20 '22 21:09

kworr