1

I'm trying to redirect all 404 messages to the index page, but only within certain directories/categories.

For example

404's within the following dir's will display as normal

www.foo.com/

www.foo.com/blah

404's in the following dir's will redirect to index.php

www.foo.com/bar

www.foo.com/fizz/buzz

So far I've found that the following will redirect all 404's to the index page with an OK status.

error_page 404 =200 /index.html

Is it possible to do this directory specifc?

1 Answer 1

1

As in the first comment, error_page can be defined in location level.

location ^~ /baz {
    error_page /index.html;
}

Old answer or another way to achieve this: You need to use try_files for this. Name is obvious. Nginx tries to open for given path if exists. if can't find, it tries the next. So your rule should look like this.

6
  • Also error_page sets all the 404s in all paths of server definition. So you can't use it.
    – risyasin
    Nov 19, 2015 at 9:38
  • 1
    that isn't true. nginx.org/en/docs/http/ngx_http_core_module.html#error_page error_page can be defined on the location level and only inherited if not defined at the current level
    – Drifter104
    Nov 19, 2015 at 9:40
  • I read that if using try_files, if any element on the page can't be loaded (such as an image or script) it'll automatically redirect - is this true?
    – jblz
    Nov 19, 2015 at 10:29
  • Also, will this be recursive? I.e anything under /baz/xxx/xxx/xxx/xx
    – jblz
    Nov 19, 2015 at 10:35
  • @Drifter104 Thank you for correcting me. you are right. it's possible to use for different locations. I am going to update my answer.
    – risyasin
    Nov 19, 2015 at 16:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .