Nginx rewrite url arguments to sub domain

By | December 7, 2017
Questions:

Have a number of different url parameter that I wish to redirect to a sub domain.

mydomain.com/blog/title-of-the-post -> blog.mydomain.com/title-of-the-post

and

mydomain-com/taxonomy/term/id -> mydomain.com/id

So the logic is pretty much a rewrite but want to grab and use some of the url. Can this be done?

Answers:

yes, you can use backreferences in your rewrites, e.g.:

location /blog/ {
   rewrite ^/blog/(.*)$ http://blog.mydomain.com/$1 permanent;
}

and the same things worksfor your other rewrite

UPDATE:

if you want to keep the blog part, you’re not changing the $uri anymore, only the $host, it then becomes easier:

location /blog/ {
  rewrite ^ http://blog.mydomain.com/$uri permanent;
}

NOTE: nginx standard variables are listed at http://wiki.nginx.org/HttpCoreModule#Variables

for multiple parameters you use further backreferences $2 $3 and so on (just make sure you have groupings, i.e. parentheses, around the parts you want to use in your regex) e.g:

location /blog/ {
  rewrite ^/blog/([0-9]{4})/(.*)$ http://blog.mydomain.com/$1/$2 permanent;
}

which would match a 4-digit year in your blog url, see for example http://www.regular-expressions.info/brackets.html for more info on regular expressions and backreferences

Leave a Reply

Your email address will not be published. Required fields are marked *