简体   繁体   English

Nginx 将动态 URL 从一条路径重定向到另一条路径

[英]Nginx redirect dynamic URLs one path to another

I want to check if a parameter is present in a url in nginx and then rewrite.我想检查一个参数是否存在于 nginx 的 url 中,然后重写。 How can i do that?我怎样才能做到这一点?

The color is dynamic in the URLs URL 中的颜色是动态的

For eg例如

  1. If url is http://website.com/lunch-box/xxxxxabc then redirect user to http://website.com/lunch-box/ .如果 url 是http://website.com/lunch-box/xxxxxabc则将用户重定向到http://website.com/lunch-box/

  2. If URL is http://website.com/lunch-box/xxxxxabc/ABCD123 no need to redirect.如果 URL 是http://website.com/lunch-box/xxxxxabc/ABCD123不需要重定向。 Need to load as it is.需要按原样加载。

I want to redirect if URL is matched.如果 URL 匹配,我想重定向。 and xxxxxabc is dynamic text. xxxxxabc是动态文本。

nginx version: nginx/1.16.1

# rewrite direct children of /lunch-box but not grandchildren+
rewrite  ^(/lunch-box/)[^/]+/?$  $1  last;

Walking through the regex ^(/lunch-box/)[^/]+/?$遍历正则表达式^(/lunch-box/)[^/]+/?$

  • ^ matches the start of a string ( rewrite rules match against the path, not the full URI) ^匹配字符串的开头( rewrite规则匹配路径,而不是完整的 URI)
  • (/lunch-box/) matches the literal text /lunch-box/ and saves it for $1 (/lunch-box/)匹配文字文本/lunch-box/并将其保存为$1
  • [^/]+ matches one or more characters that are not a forward slash [^/]+匹配一个或多个不是正斜杠的字符
  • /? matches zero or one forward slash匹配零个或一个正斜杠
  • $ matches the end of the string $匹配字符串的结尾

This strips off the path past what we've saved as $1 , but only when that path is a direct child.这将去掉我们保存为$1路径,但前提是该路径是直接子路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM