Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace underscores in unknown subdomains with dashes in an nginx redirect

Tags:

redirect

nginx

I've got URLs coming in that look like this:

https://some_sub_domain.whatever.com

That need to be redirected to:

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

I don't know what the subdomains will be (they're usernames).

While I need to replace underscores for the subdomain, I need to leave other underscores in-tact:

https://some_sub_domain.whatever.com/hey_there_underscore

Should redirect to:

https://some-sub-domain.whatever.com/hey_there_underscore
like image 561
Nick Sergeant Avatar asked Jan 28 '13 17:01

Nick Sergeant


1 Answers

Here's a way to 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;
}
like image 154
Evan Avatar answered Nov 26 '22 22:11

Evan