Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I'm trying to redirect a subfolder to a subdomain in nginx. I want http://example.com/~meow/ to be redirected to http://meow.example.com/. I tried the following:

location ~ ^/\~meow/(.*)$ {
    rewrite ^(.*)$ http://meow.example.com$1 permanent;
}

But it doesn't work. It gets caught by my location block for user directories:

location ~ ^/~([^/]+)/(.+\.php)$ {
    [...]
}

and

location ~ ^/\~([^/]+)/(.*)$ {
    [...]
}

So, how would I do this? Oh, and I only want /~meow/ to be redirected. All other user directories should not be changed.

share|improve this question

3 Answers 3

up vote 3 down vote accepted

You could try using nested location like this

location ~ ^/\~([^/]+)/(.*)$ {
  location ~ ^/\~meow/(.*)$ {
    rewrite ^(.*)$ http://meow.example.com$1 permanent;     
  }
  [...]
}
share|improve this answer
    
+1 for nested. These things have a way of growing out of proportion over time and keeping it nested means you're not scratching your head what you missed that prevents it from working. –  Mel May 16 '11 at 0:11

A static location would be more efficient for what you're asking. If you read the four rules at http://wiki.nginx.org/HttpCoreModule#location , you'll see that a locaion ^~ will not be overridden by a regex location. You also seem to want to strip the leading /~meow while redirecting. The correct approach would be:

location ^~ /~meow/ {
  rewrite ^/~meow(.*) http://meow.example.com$1 permanent;
}

As an aside, there's no reason to capture the entire uri when rewriting. The current uri is already saved in $uri.

rewrite ^(.*)$ http://meow.example.com$1 permanent;

and

rewrite ^ http://meow.example.com$uri permanent;

will always produce the same result, and the second rewrite is more efficient, since it's a short circuited match and already contains what you're trying to capture anyway.

share|improve this answer
    
Excellent with the one liners! + Repped –  TheBlackBenzKid Feb 19 '13 at 16:52

Regexp locations are checked in the order of their appearance in the configuration file and the first positive match is used. Which means, your location ~ ^/\~meow/(.*)$ must be above other two locations in the configuration file.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.