如果不相等,则 Nginx 位置匹配

如果不相等,则 Nginx 位置匹配

我有 www.example.com/test,我想编写一个条件,如果请求的 URL 不等于 /test,则进行重写或重定向到 www.example.com。我能得到最接近的代码是下面的代码,但是当我想使用末尾不带 / 的 www.example.com/test 时,它会将我重定向到 www.example.com,但当我输入 www.example.com/test/ 时,它就可以正常工作。

location / 
fastcgi_param  REQUEST_URI $request_uri;
fastcgi_param  HTTPS on;

if ($request_uri !~ ^/test/(.*)$)
{return 301 $scheme://www.example.com;}

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

答案1

Nginx 如果

通常使用 Nginx避免使用 IF 语句。它需要更多的资源,并且并不总是能按照你想要的方式运作。

解决方案

执行此操作的方法是定义两个位置,catchall 和 test。

# I just copied this from above, you might want it in a block
fastcgi_param  REQUEST_URI $request_uri;
fastcgi_param  HTTPS on;

# Return permanent redirect for everything other than the /test URL
# Suggest you use 302 until you have this working perfectly. Google / browsers
# caches 301 redirects for a long time
location / {
  return 301 $scheme://www.example.com;
}

location /test {
 try_files $uri $uri/ /index.php$is_args$args;
}

我认为这对 /test 和 /test/ 都有效。如果不行,你可以试试这个,可能会有用

location ~* /test

你应该了解一下 Nginx 的工作原理,特别是位置块匹配。我认为这篇文章可能会有用

相关内容