nginx redirect all directories except one

Viewed 40367

I'm using nginx 1.0.8 and I'm trying to redirect all visitors from www.mysite.com/dir to google search page http://www.google.com/search?q=dir where dir is a variable, however if dir=="blog"( www.mysite.com/blog) I just want to load the blog content(Wordpress).

Here is my config :

    location / {
        root   html;
        index  index.html index.htm index.php;
    }



    location /blog {
          root   html;
          index index.php;
          try_files $uri $uri/ /blog/index.php;
    }

    location ~ ^/(.*)$ {
          root   html;
          rewrite ^/(.*) http://www.google.com/search?q=$1 permanent;
    }

if I do this even www.mysite.com/blog will be redirected to google search page. If I delete the last location www.mysite.com/blog works great.

From what I've read here: http://wiki.nginx.org/HttpCoreModule#location it seems that the priority will be first on regular expressions and that first regular expression that matches the query will stop the search.

Thanks

2 Answers

This situation can also be handled using only regex. Though this is a very old question and it has been marked answered, I'm adding another solution.

If you use multiple loop forwards using reverse proxy this is the easiest way without having to add a separate location block for every directory.

root html;
index index.php;

location / { #Match all dir
      try_files $uri $uri/ $uri/index.php;
}

location ~ /(?!blog|item2)(.*)$ { #Match all dir except those dir items skipped
      rewrite ^/(.*) http://www.google.com/search?q=$1 permanent;
}
Related