2

I have this NGINX configuration:

root    /var/www/web;
index   index.php;

server_name  domain.com;
access_log  off;
error_log on;

location / {
    rewrite ^/(.*)$ /index.php?tag=$1&page=1 last;
}

Now, I want to redirect url something like "domain.com/index.php?tag=1&section=2&type=3" to "domain.com/tag/section/type"

how can I do that, where should I put the code? please help,

Thankyou

I already tried:

location / {
   rewrite ^/index\.php?tag=(.*)&section=(.*)&type=(.*)$ /$1/$2/$3 permanent;
   rewrite ^/(.*)$ /index.php?tag=$1&page=1 last;
}

but it didnt work..

RaiN
  • 152
  • 1
  • 9
  • See [this answer](https://stackoverflow.com/questions/49191594/nginx-rewrite-a-lot-2000-of-urls-with-parameters/49192527#49192527) – Richard Smith Jan 23 '19 at 14:44
  • what about the variables? what should I write for the redirect? I tried but still not workin.. – RaiN Jan 23 '19 at 15:40

1 Answers1

4

The rewrite and location directives use a normalized URI which does not include the query string.

To test the query string, you will need to consult the $request_uri or $args variable using an if statement and/or map directive.

The advantage of using $request_uri is that it contains the original request and will help to avoid a redirection loop.

If you only have one redirection to perform, the map solution is probably overfill.

Try:

if ($request_uri ~ ^/index\.php\?tag=(.*)&section=(.*)&type=(.*)$) {
    return 301 /$1/$2/$3;
}
location / {
    ...
}

See this caution on the use of if.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • thanks, this is exactly what I am lookin for.. and I just realized should put the code outside the location.. – RaiN Jan 23 '19 at 15:58