Score:0

Nginx rewrite using $args to create a shorter url with parameters

cd flag

My scenario is this:

For 20+ years I've used the following URL for search result on a old website:

https://www.example.com/cgi-bin/website.cgi?type=search_result&query=examplequery
https://www.example.com/cgi-bin/website.cgi?type=search_result&query=examplequery&page=72

I would like to start using a new, shorter url for search results, like this:

https://www.example.com/?q=examplequery
https://www.example.com/?q=examplequery&p=72

I would also like the old URLs to permanent redirect to the new URL, if possible.

This is what I have tried, after searching for a solution (this is in the location block in nginx.conf).

if ($args ~ "^/?q=val1&p=val2") {
   rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$arg_q&page=$arg_p? last;
}
if ($args ~ "^/?q=val1") {
   rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$arg_q? last;
}

For some reason, this is not working. I don't get any error.

In order to redirect old urls to the new format, I will use:

if ($args ~ "type=search_result&query=$val1&page=$val2") {
   rewrite ^ /&q=$arg_query&p=$arg_page? permanent;
}
if ($args ~ "type=search_result&query=$val1") {
   rewrite ^ /&q=$arg_query? permanent;
}

Not sure if this is working or not, since it depends on the above statements, I have not been able to test. But I don't get any errors.

I'm not sure that I'm doing wrong. If someone could have a look I would be very greatful.

Richard Smith avatar
jp flag
`$args` will not match `^/?q=val1&p=val2`. It might match `^q=.*&p=`
Richard Smith avatar
jp flag
You may need to add the `location` block that handles the `/cgi-bin/website.cgi` URL so that we can understand how the argument list is passed to the script.
Niska avatar
cd flag
@RichardSmith I don't understand your comment. What am I doing wrong?
sv flag
Welcome to ServerFault. It is better to handle one issue at a time. You'd want to take consider 301 redirects as a separate question once the issue with shorter URLs are resolved!
Score:0
cd flag

I got it working!

if ($args ~ "^q=([^&]+)$") {
  set $q $1;
  rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$1 last;
}

if ($args ~ "^q=([^&]+)&p=(\d+)") {
  set $q $1;
  set $p $2;
  rewrite ^ /cgi-bin/website.cgi?type=search_result&query=$1&page=$2 last;
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.