1

I want to check if a parameter is present in a url in nginx and then rewrite. How can i do that?

The color is dynamic in the URLs

For e.g

  1. If url is http://website.com/lunch-box/xxxxxabc then redirect user to http://website.com/lunch-box/.

  2. If URL is http://website.com/lunch-box/xxxxxabc/ABCD123 no need to redirect. Need to load as it is.

I want to redirect if URL is matched. and xxxxxabc is dynamic text.

nginx version: nginx/1.16.1

Vel
  • 9,027
  • 6
  • 34
  • 66
  • Am I missing something? This isn't a parameter (GET/POST) and your second bullet points to itself. Maybe you want `RewriteRule /lunch-box/([^/]+)/(.*) /lunch-box/script.cgi?color=$1&extra=$2`? – Adam Katz Mar 23 '20 at 20:48
  • @AdamKatz, I don't want in color and extra parameters. I want to redirect without query string. – Vel Mar 24 '20 at 05:57
  • Okay, I see you've cleaned up the question. This appears sufficient to produce an answer. See below. – Adam Katz Mar 24 '20 at 18:00

1 Answers1

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

Walking through the regex ^(/lunch-box/)[^/]+/?$

  • ^ matches the start of a string (rewrite rules match against the path, not the full URI)
  • (/lunch-box/) matches the literal text /lunch-box/ and saves it for $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.

Vel
  • 9,027
  • 6
  • 34
  • 66
Adam Katz
  • 14,455
  • 5
  • 68
  • 83
  • Is it inside a `server` or `location` stanza? See the official [Creating NGINX Rewrite Rules](https://www.nginx.com/blog/creating-nginx-rewrite-rules/) documentation or the answers to [How to write a url rewrite in nginx](https://stackoverflow.com/q/4329316/519360). – Adam Katz Mar 25 '20 at 15:06
  • it is inside a server. not in location. – Vel Mar 25 '20 at 15:08
  • I'm not an NGINX expert, but I'd suggest looking through the logs and if that's insufficient, increase the log level. From the docs, my syntax looks right and my regex should be fully supported. – Adam Katz Mar 25 '20 at 15:09
  • there is no error in your code. but it is not redirect. – Vel Mar 25 '20 at 15:17