Search code examples
http-redirectnginxtrailing-slash

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


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/;
  }

}


Solution

  • 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;
      }