1

I want to redirect URLs with slash to the path without trailing slash. So /some-url/ to /some-url for Duplicate Content Issue

And the rest of the URLs, like

/some-url.xml
/some-url?
/some-url/?
/some-url?q=v
/some-url/?q=v
/some-url

Should stay without redirection. i want exactly opposite to following question. How to configure redirects to url with trailing slash in nginx?

Naisa purushotham
  • 905
  • 10
  • 18

2 Answers2

0

Please consider trying inside your server block:

rewrite ^/(.*)/$ /$1 permanent;

via: https://www.scalescale.com/tips/nginx/nginx-remove-trailing-slash/

This looks for anything with a request URI starting with a '/' and ending with a slash (the '$' at the end of the search section immediately after the rewrite) and replaces it with the '/' at the beginning and the URI without the ending slash at the end. The final part indicates that it will serve 301 redirects.

Update: To avoid removing the slash from URIs with GET parameters, please try:

if ($query_string != "") {
    rewrite ^/(.*)/$ /$1 permanent;
}

It's generally not recommended to use if statements, but if you were to use a map like this:

map $query_string $trailing_slash {
    ""  ""
    default "/";
}
rewrite ^/(.*)/$ /$1$trailing_slash permanent;

it would result in infinite redirects for any string with a query, since it would redirect to itself (both source and destination would have the trailing slash in them). Therefore, we need to use a conditional for the rewrite.

0

After verifying all the nginx configuration i dint find any else condition and any AND (&&) conditions. finally i did with "set" property in nginx

  set $val 0;
  if ($request_method ~ "^GET$"){
      set $val 1;
   }

  if ($request_uri ~ ^/(.*)/$ ) {
   set $val "${val}1";
  }

  location / {
          if ($val ~ 11) { rewrite ^/(.*)/$ https://$host/$1; }
          try_files $uri $uri/ /index.php$is_args$args;
  }  
Naisa purushotham
  • 905
  • 10
  • 18