1

I'm trying to rewrite

  1. web.com/ab to web.com?sys=ab
  2. web.com/ab/cd to web.com?sys=ab&id=cd
  3. web.com is unchanged.

I've written the following:

rewrite ^/(\w+)(/?\w*)$ /?system=$1&id=$2 break;
Leeloo
  • 350
  • 6
  • 20
  • I cannot make this fail. Do you clear the browser's cache between tests? A stale cache can cause unpredictable results. – Richard Smith Aug 07 '17 at 11:09
  • @RichardSmith Yes, of course. I tested writing `?system=test&id=5` it worked, but `/test/5` doesn't – Leeloo Aug 07 '17 at 11:19
  • @RichardSmith It tries to find my js/css files in `/test/` when I access `/test/5`! `Unable to find web.com/test/user.css`. Rewriting is incorrect.. – Leeloo Aug 07 '17 at 11:22
  • That is a different problem. If you use path-relative URIs for resource files **and** use routes that "look-like" sub-directories, the browser is going to request the resource file by prefixing the apparent sub-directory. You need to use path-absolute resource files with this kind of scheme. – Richard Smith Aug 07 '17 at 11:27
  • @RichardSmith But if the URL is rewritten, browser should see `?system=2&id=5`, not subdirectory... – Leeloo Aug 07 '17 at 11:29
  • No. Browser sees what is written in the *address bar*. If you want the browser to see your rewritten URL you need to use a redirect (like your last rewrite statement) - in which case the *address bar* will necessarily change. At the moment, you are only changing the URL within `nginx`. – Richard Smith Aug 07 '17 at 11:33
  • @RichardSmith Thanks. So, If I want the URL to be in this way, I can't use relative path for js/css? No way? – Leeloo Aug 07 '17 at 11:40
  • You could try using an HTML `base` tag, but it may just add a whole lot of new problems. See [this question](https://stackoverflow.com/questions/1889076/is-it-recommended-to-use-the-base-html-tag) for details. – Richard Smith Aug 07 '17 at 11:46
  • Great! Thanks... – Leeloo Aug 07 '17 at 12:53

1 Answers1

1

Testing your rewrite statement, I get:

  1. web.com/ab to web.com?sys=ab&id=
  2. web.com/ab/cd to web.com?sys=ab&id=/cd
  3. web.com is unchanged.

You can fix (2) by moving the parentheses so that the second / is not captured. The simplest way to fix (1) is to replace your one rewrite statement with two:

rewrite ^/(\w+)/(\w*)$ /?system=$1&id=$2 break;
rewrite ^/(\w+)$       /?system=$1       break;
Richard Smith
  • 45,711
  • 6
  • 82
  • 81