3

Currently I have a main redirect to the home of my webserver. However I would like to treat the subpaths with redirect after a 404 was not for the home and yes for the subpath, that with multiple subpaths. That not to repeat the rules, I must deal with a REGEX, however I don't know how to insert these rules and return to the current subpath.

home

www.foo.com.br

subpath

www.foo.com.br/machine
www.foo.com.br/cloud
www.foo.com.br/air

today

# define error page
error_page 404 = @notfound;

# error page location redirect 301
location @notfound {
    return 301 /;
}

would like answer 404

www.foo.com.br/machine/test123  

go to

www.foo.com.br/machine/

2 Answers2

1

The REGEX used to pick up the first field and redirect after a 404:

  error_page 404 = @notfound;

  location @notfound {
    rewrite ^/([\w-]*)/.* /$1/ permanent;

In your php block put the fastcgi_intercept_errors set to on

  location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    # intercept errors for 404 redirect
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  }
0

You can add rewrite rules before the return statement to match the specific subdirectories you want treated differently.

For example:

location @notfound {
    rewrite ^/(machine|cloud|air)/. /$1/ permanent;
    return 301 /;
}

See this document for details.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • Richard, thanks for the reply. The regex created was as follows: ```error_page 404 = @notfound;    location @notfound {      rewrite ^/([\w-]*)/.* /$1 permanent;    } ``` The expected result is the first field if the url doesn't exist. it's working. But I have another problem, when doing the redirect this is downloading the `index.html` from the home page. Have you saw anything like this? – Vinicius Peres Apr 08 '19 at 14:59
  • You can test the redirection using `curl -I`, but you are probably missing a trailing `/` in the rewritten URI. – Richard Smith Apr 08 '19 at 15:26
  • Thank you, you're correct. I'll close this case. I realized that to do the redirect is just taking everything that is * .php, then yes everything works ok, but if I try with a normal path `foo.com.br/air/` is not going, and downloading `index .html` from the home page. I think it's the `try_files` config. – Vinicius Peres Apr 09 '19 at 09:16
  • Richard, This worked great! Thanks! If you can take a look, please. [link](https://stackoverflow.com/questions/55589837/how-to-insert-read-path-in-try-files-rewrite-error-in-nginx) – Vinicius Peres Apr 09 '19 at 09:50