Pavel Reznikov
Pavel Reznikov

Reputation: 3208

Nginx: moving site to new domain

I have a site example.com that runs wordpress. Now I want to move this blog to subdomain blog.example.com, but also I want following:

example.com --> static page (not wordpress)

blog.example.com --> new address to the blog
blog.example.com/foo --> handled by wordpress

example.com/foo --> permanent redirect to blog.example.com/foo

So I tried this next config:

    server {
            server_name example.com;

            location = / {
                    root /home/path/to/site;
            }

            location / {
                    rewrite ^(.+) http://blog.example.com$request_uri? permanent;
            }
    }

In this case redirection is working perfectly. Unfortunately example.com redirects to blog.example.com too.

Upvotes: 1

Views: 1200

Answers (2)

Tisho
Tisho

Reputation: 8502

As long as the root of the two domains will point to different directories, you'll need two server directives - something like this:

server {
        # this is the static site
        server_name example.com;

        location = / {
                root /home/path/to/static/page;
        }

        location /foo {
                return 301 http://blog.example.com$request_uri;
        }
}

server {
        # this is the WP site
        server_name blog.example.com;

        location = / {
                root /home/path/to/new_blog;
        }

        .... some other WP redirects .....
}

Upvotes: 1

kolbyjack
kolbyjack

Reputation: 18310

The reason it's redirecting is because when it tries to load the index file of example.com, it performs an internal redirect to /index.html, which is handled by your rewriting location. To avoid this, you can use try_files:

server {
  server_name example.com;

  root /home/path/to/site;

  location = / {
    # Change /index.html to whatever your static filename is
    try_files /index.html =404;
  }

  location / {
    return 301 http://blog.example.com$request_uri;
  }
}

Upvotes: 2

Related Questions