Home > database >  Appending query parameters to specific URI
Appending query parameters to specific URI

Time:03-01

I'm trying to append the query string ?sort_by=id&dir=ASC&lim=2&flt=1 to any traffic going to /admin/users.php, which should result in:

/admin/users.php?sort_by=id&dir=ASC&lim=2&flt=1

I was attempting to follow this question/answer:

https://serverfault.com/questions/311487/nginx-rewrite-append-a-parameter-at-the-end-of-an-url

By doing the following:

location /admin/users.php {
  rewrite  ^(.*) $1?sort_by=id&dir=ASC&lim=2&flt=1 break;
}

Also tried:

  location /admin/users.php {
    rewrite  ^ /admin/users.php?sort_by=id&dir=ASC&lim=2&flt=1 last;
  }

But any traffic going to /admin/users.php comes back without the query string added. I'm obviously doing something wrong.

Any suggestions for implementing this correctly?


The default.conf in its entirety:

server {
  listen 4000;
  root   /usr/share/nginx/html/src;

  include /etc/nginx/default.d/*.conf;

  index app.php index.php index.html index.htm;

  client_max_body_size 500m;


  location ~ [^/]\.php(/|$) {
    fastcgi_split_path_info ^(. ?\.php)(/.*)$;
    rewrite  ^/admin/?(.*) /$1 break;
    rewrite ^/admin/users.php$ /admin/users.php?sort_by=id&dir=ASC&lim=2&flt=1 break;
    fastcgi_param HTTP_PROXY "";
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
  }
}

CodePudding user response:

Since you are trying to rewrite an URI of the PHP file, most likely you have a PHP handler looking somewhat like

location ~ \.php$ {
    ...
}

The ~ modifier specifies a regex matching location, and locations of that type have a greater priority than the prefix ones (only exact match locations with the = modifier have greater priority than the regex ones). Moreover, you should not try to do it with the additional location block - all that you can achieve with that approach is the endless loop. Try this instead:

location ~ \.php$ {
    rewrite ^/admin/users.php$ /admin/users.php?sort_by=id&dir=ASC&lim=2&flt=1 break;
    include fastcgi_params;
    ...
}

Update

You have two rewrite directives in your PHP handler location. The first one will truncate the /admin prefix from any URI that start with that prefix. The second one will add additional query arguments to /admin/users.php URI, but it will be already rewritten to the /users.php. Moreover both rewrite directives have a break flag which means that if the first rule will be executed, the second one will never be reached. To combine both rules, try the following preserving the rewrite directives order:

rewrite ^/admin/users.php$ /users.php?sort_by=id&dir=ASC&lim=2&flt=1 break;
rewrite ^/admin/?(.*) /$1 break;
  • Related