Replace underscores in unknown dash subdomains in nginx redirection

I have urls that look like this:

https://some_sub_domain.whatever.com

To do this, redirect to:

https://some-sub-domain.whatever.com

I do not know what subdomains will be (they are usernames).

While I need to replace underscores for a subdomain, I need to leave other underscores in tactics:

https://some_sub_domain.whatever.com/hey_there_underscore

Redirect to:

https://some-sub-domain.whatever.com/hey_there_underscore
+5
source share
2 answers

Here you can rewrite via lua:

location / {
  rewrite_by_lua '
  if string.find(ngx.var.host, "_") then
    local newHost, n = ngx.re.gsub(ngx.var.host, "_", "-")
    ngx.redirect(ngx.var.scheme .. "://" .. newHost .. ngx.var.uri)
  end
  ';
  proxy_pass       http://my_backend;
  proxy_set_header Host $host;
}
+6
source

Assuming no. you can use regular expressions in the username:

(https?://)([a-zA-Z0-9_]+)(\..*)

, . perl- favoretti , , , nginx perl-.

0

All Articles