Nginx:将网站迁移到新域名

时间:2012-07-12 22:12:38

标签: nginx

我有一个运行wordpress的网站example.com。现在我想将此博客移至子域blog.example.com,但我也想要关注:

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

所以我尝试了下一个配置:

    server {
            server_name example.com;

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

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

在这种情况下,重定向工作正常。不幸的是,example.com也会重定向到blog.example.com。

2 个答案:

答案 0 :(得分:2)

它重定向的原因是因为当它尝试加载example.com的索引​​文件时,它会执行内部重定向到/index.html,这由您的重写位置处理。为避免这种情况,您可以使用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;
  }
}

答案 1 :(得分:1)

只要两个域的根目录指向不同的目录,就需要两个server指令 - 如下所示:

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 .....
}