How to configure redirects to url with trailing slash in nginx?

孤者浪人 提交于 2019-12-05 16:46:21

This should solve the problem:

location / {
    if ($request_uri ~ ^([^.\?]*[^/])$) {
        return 301 $1/;
    }

    try_files $uri $uri/ /index.php$is_args$args;
}

The query string begins at the ? and is not part of the normalized URI used when matching location and rewrite directives. The entire URI is available as the $request_uri variable. You could use your regular expression within an if block:

if ($request_uri ~ ^([^.?]*[^/])$ ) { return 301 $1/; }

See this document for more, and this caution on the use of if.

I figured out how to do this without an if statement! This solves all the problems you mentioned (except case #2, and in case #3 it redirects but retains the query string).

# 301 try_file for trailing slash
location ~ ^([^.\?]*[^/])$ {
  try_files $uri @addslash;
}

# 301 redirect for trailing slash
location @addslash {
  return 301 $uri/$is_args$args;
}

# Root directory location handler
location / {
    try_files $uri/index.html $uri $uri/ /index.php?$query_string;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!