我将使用哪个重定向规则来重定向olddomain下的所有页面。示例被重定向到newdomain.example?

该网站有一个完全不同的结构,所以我想在旧域下的每个页面都被重定向到新的域索引页。

我认为这将(在旧域。例如基本目录):

RewriteEngine On
RewriteRule ^(.*)$ http://newdomain.example/ [R=301]

但如果我导航到olddomain。我被重定向到newdomain.example/somepage。我期待重定向到newdomain。不带页后缀的示例。

我怎么才能不提最后一部分?


当前回答

我作为SymLinks的解决方案在我的服务器上不起作用,所以我在我的PHP中使用了一个If。

function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
$redirect = str_replace("www.", "", curPageURL());
$remove_http_root    = str_replace('http://', '', $redirect);
$split_url_array     = explode('/', $remove_http_root );


if($split_url_array[0] == "olddomain.com"){
    header("Location: http://www.newdomain.com/$split_url_array[1]");
    die();
}

其他回答

这是apache旧版本中的一个错误(因此mod_rewrite),如果路径被更改,路径前缀会附加到重写的路径上。在这里看到的

我认为它在apache2 V2.2.12中被修复了,有一个你需要使用的特殊标志,当我找到它时,我会在这里添加它,(我认为它是NP for No Path)

RewriteRule ^(.*)$ http://newdomain.com/ [??]

只是为了澄清,在删除托管重定向这是在路上,我原来的解决方案也起作用:

RewriteEngine On
RewriteRule ^(.*)$ http://newdomain.com/ [R=301]

我作为SymLinks的解决方案在我的服务器上不起作用,所以我在我的PHP中使用了一个If。

function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
$redirect = str_replace("www.", "", curPageURL());
$remove_http_root    = str_replace('http://', '', $redirect);
$split_url_array     = explode('/', $remove_http_root );


if($split_url_array[0] == "olddomain.com"){
    header("Location: http://www.newdomain.com/$split_url_array[1]");
    die();
}

使用条件重定向选项-FollowSymLinks和AllowOverride -Options被主机禁用,如果一些本地文件也应该服务:

示例. htaccess

# Redirect everything except index.html to http://foo
<FilesMatch "(?<!index\.html)$">
    Redirect 301 / http://foo/
</FilesMatch>

这个例子将提供本地index.html并将所有其他人员重定向到新域。

尝试这种方法重定向到主页新域,它为我工作:

RewriteCond %{HTTP_HOST} ^olddomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.olddomain\.com$
RewriteRule ^(.*)$ "https\:\/\/newdomain\.com\/" [R=301,L]