I have this instance where a html search <form>
forces it to go to /search/index.php?q=term
and would like to use something like /search/term
instead.
This is how the config looks like right now:
location /search/ {
rewrite ^/search/(.+) /search/index.php?q=$1;
}
Accessing this location directly works, but in the moment of filling out the form, and searching it will use the "origin" rather than the rewrite.
I tried using redirect "backwards", but that crashed the nginx service:
location /search/ {
rewrite ^/search/(.+) /search/index.php?q=$1;
redirect ^/search/index.php?q=(.+) /search/$1;
}
I also tried rewrite with permanent
flag, which didn't do anything
location /search/ {
rewrite ^/search/(.+) /search/index.php?q=$1;
rewrite ^/search/index.php?q=(.+) /search/$1 permanent;
}
I know it's possible to achieve the same thing in PHP with something like this:
// On the top of /search/index.php
if (str_starts_with($_SERVER['REQUEST_URI'], '/search/index.php')){
$protocol = ($_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") ? "https" : "http";
$server = $_SERVER['HTTP_HOST'];
$queries = array();
parse_str($_SERVER['QUERY_STRING'], $queries);
$search = $queries['q'] ?? "";
header("Location: $protocol://$server/search/$search");
}
But think it would be better if nginx could handle this (if it's possible at all).
Does anyone know how to rewrite, and redirect access from the origin ?