How to replace characters in an nginx variable string?

nginx substring
nginx variable substitution
nginx rewrite
nginx rewrite append query string
nginx find replace
nginx map
nginx rewrite query string
nginx rewrite request_uri

Is there a way I can replace non alphanumeric characters returned with $request_uri with a space (or a +)?

What I'm trying to do is redirect all 404's in one of my sites to it's search engine, where the query is the uri requested. So, I have a block in my nginx.conf containing:

error_page 404 = @notfound;
location @notfound {
    return 301 $scheme://$host/?s=$request_uri;
}

While this does indeed work, the url's it's returning are the actual uri's complete with -_/ characters causing the search to always return 0 results

For instance... give this url: https://example.com/my-articles, the redirect ends up as this: https://example.com/?s=/my-articles

What I would like is to end up (ultimately) like this: https://example.com/?s=my+articles (tho, the + at the beginning works fine too... https://example.com/?s=+my+articles

I will need to do this without LUA or Perl modules. So, how can I accomplish this?

You may need to tweak this depending upon how far down your directory structure you want the replacement to go, but this is the basic concept.

Named location for initial capture of 404s:

location @notfound {
  rewrite (.*) /search$1 last;
}

Named locations are a bit limiting, so all this does is add /search/ to the beginning of the URI which returned 404. The last flag tells Nginx to break out of the current location and select the best location to process the request based on the rewritten URI, so we need a block to catch that:

location ^~ /search/ {
  internal;
  rewrite ^/search/(.*)([^a-z0-9\+])(.*)$ /search/$1+$3 last;
  rewrite ^/search/(.*)$ /?s=$1 permanent;
}

The internal directive makes this location only accessible to the Nginx process itself, any client requests to this block will return 404.

The first rewrite will change the last non text, digit or + character into a + and then ask Nginx to reevaluate the rewritten URI.

The location block is defined with the ^~ modifier, which means requests matching this location will not be evaluated against any regex defined location blocks, so this block should keep catching the rewritten requests.

Once all the non word characters are gone the first rewrite will no longer match so the request will be passed to the next rewrite, which removes the /search from the front of the URI and adds the query string.

My logs look like this:

>> curl -L -v http://127.0.0.1/users-forum-name.1
<<  "GET /?s=users+forum+name+1 HTTP/1.1"

>> curl -L -v http://127.0.0.1/users-forum-name/long-story/some_underscore
<< "GET /?s=users+forum+name+long+story+some+underscore"

You get the idea..

Substitutions, subs_filter allows replacing source string (regular expression or fixed) in the NGINX response with destination string. Substitution text may contain variables. While this is probably a suitable solution when the number of characters to replace is small compared to the length of the string, it doesn't scale well. As the proportion of characters in the original string that need to be replaced increases, this method will approach O(N^2) in time. – andand May 24 '10 at 14:37

You can use lua module, transform this variable to what you need using lua string functions. I'am using OpenResty which is basicly nginx with lua enabled. But nginx lua module will do fine. Here is directive that allows you to use lua inside nginx configuration. It could be inside location using content_by_lua_block / access_by_lua_block or in separate file using content_by_lua_file / access_by_lua_file. Here is documentation on this https://github.com/openresty/lua-nginx-module#content_by_lua . Here is an example from my app.

location ~/.*\.jpg$ {

  set $test '';
  access_by_lua_block {

    ngx.var.test = string.sub(ngx.var.uri, 2)

  }
  root /var/www/luaProject/img/;
  try_files    $uri /index.html;


  }

nginx: String Replace plus sign with hyphen, This will replace the plus with a hyphen for you: location ^~ /city/ { # For the single word case, just copy the city name set $city $arg_sl_city;  Translate, squeeze, and/or delete characters from standard input, writ‐ ing to standard output. improve this answer. edited May 8 '11 at 15:05. answered May 8 '11 at 14:56. 732 silver badges. 772 bronze badges. While this works for the question as it was asked, it's less general than the accepted answer (which works on character replacement

How to replace character in URL in nginx? - nginx - iOS, Nginx: how to search and replace string variables like str_replace. I'm new with nginx and before this question search too much. I want to set a variable equal to  Because this method returns the modified string, you can chain together successive calls to the Replace method to perform multiple replacements on the original string. Method calls are executed from left to right. The following example provides an illustration. String s = "aaa" ; Console.WriteLine ( "The initial string: ' {0}'", s); s = s

Module ngx_http_sub_module, The string to replace (1.9.4) and replacement string can contain variables. Several sub_filter directives can be specified on one configuration level (1.9.4). These  Similarly, replace text in strings with the replace function, or extract text with functions such as extractBetween. You can use any of these functions with either character vectors or string arrays. For compatibility, you can also use functions such as strfind and strrep with both character vectors and string arrays.

Nginx, a variable name; false if the value of a variable is an empty string or “0”; regular expression includes the “}” or “;” characters, the whole expressions should be  C Program to Replace All Occurrence of a Character in a String Example 1. This program allows the user to enter a string (or character array), and a character value. Next, it will search and replace all occurrence of a character inside a string. First we used For Loop to iterate each and every character in a String.

Nginx Rewrite URL Rules Examples, NGINX rewrite rules are used to change entire or a part of the URL requested by a The two variables used in the above return directive are $scheme and against the requested URI then the replacement string is used to change the To define the pattern, the characters ^,? and $ are used and have special meaning. For C strings, nginx uses the unsigned character type pointer u_char *. The nginx string type ngx_str_t is defined as follows: typedef struct { size_t len; u_char *data; } ngx_str_t; The len field holds the string length and data holds the string data. The string, held in ngx_str_t, may or may not be null-terminated after the len bytes. In most

Comments
  • will you give some other samples (urls)
  • make them up as you go mate... the question is detailed enough
  • hmm... for some reason this is not working for me. you can test with: https://gyo.im/this-is-a-dummy?_=12
  • hmm.... so, I had to add fastcgi_intercept_errors, in order to get started with processing the 404, however, it presents me with https://gyo.im/?s=index+php&q=/this-is-a-dummy&_=12
  • Your initial request has a query string, so you'll need to get rid of that. Either add a ? or using set $args ''; index.php is appearing from somewhere, so guess you have it specified in an index or try_files directive?
  • for the time being I have implemented a hybrid redirect. using the nginx config I posted, but redirecting to a php file that cleans the input, does the string replacement, then the redirect
  • I will need to do this without LUA or Perl modules. So, how can I accomplish this?
  • Without LUA I would try to do rewrite just like other anwsers show. Why not just use modules?
  • Sorry mate, #1 is useless, per the question. I do not need opinion's... I asked a question looking for an answer.... if I wanted opinions, I would have hit Facebook. #2 It's a wordpress site. #3, I will look those over... as I stated in another comment, I have a work around inplace for now