Add slash to redirect if URL is not ending with slash in Nginx

2.3k Views Asked by At

I wanted to add a slash to a redirect URL because the target (Wordpress) also redirects if the url does not end with a slash. This would result in two redirects.

My current config doesn't seem to work

server {
  listen 80;
  server_name old.domain.com;

  location ~ ^(.*)[/]$ {
    return 302 https://new.domain.com/$request_uri;
  }

  location ~ ^(.*)[^/]$ {
    return 302 https://new.domain.com/$request_uri/;
  }

}

1

There are 1 best solutions below

0
On BEST ANSWER

Try to put url with '/' before without '/', might it matching with first without slash and redirecting it

Try this

server {
  listen 80;
  server_name old.domain.com;

  location ~ ^(.*)[/]$ {
    return 302 https://new.domain.com/$request_uri/;
  }

  location ~ ^(.*)[^/]$ {
    return 302 https://new.domain.com/$request_uri;
  }