将网站重定向到内部链接

时间:2016-09-08 12:42:41

标签: php .htaccess redirect

我有一个多语言网站,其结构为http://www.url.com/en/http://www.url.com/it/http://www.url.com/pt/等。 我现在的问题是当你访问链接url.com时,我将有3个重定向。

  1. http://url.com
  2. http://www.url.com
  3. http://www.url.com/en/
  4. 如何只有2次重定向?如果您访问http://url.com以重定向到http://www.url.com/en/ 在我的htaccess文件中,我有这些行。

    RewriteCond %{HTTP_HOST} ^url.com [NC]
    RewriteRule ^(.*)$ http://www.url.com/$1 [L,R=301]
    

    此网址从url.com重定向到http://www.url.com。重定向后,一个php文件脚本识别该域,并再次重定向到/ en /

    $url= strpos($_SERVER['REQUEST_URI'],"/".$lang."/");
    if($url!==0){ Header( "HTTP/1.1 301 Moved Permanently" ); 
    Header( "Location: http://www.url.com/en/" );  }
    

    之后我有条件检查你是否使用其他语言。

    if($lang == "pt"){$langcheck = "pt"}
    

    我的链接是这样创建的:

    RewriteRule ^([_A-Za-z0-9-]+)\/$ index.php?page=index&lang=$1 [L]
    

    那么我应该在htaccess中写什么来为每种语言工作呢。因为如果我将RewriteRule更改为url.com/en/,则其他语言将不再起作用。

1 个答案:

答案 0 :(得分:0)

如何完成此操作取决于您从何处获取语言字符串,您希望支持多少种语言,以及此交互应该有多复杂。

如果它只是几种语言,而您想使用浏览器设置,则可以使用htaccess rewrites

但是,如果您拥有的语言不仅仅是几种,那么您希望让用户在网站本身中选择自己的语言,或者比上述更复杂的语言。那么,你需要用PHP做一切 这意味着删除了缺失的" www" htaccess重定向。域,然后在PHP代码中检查这一点。在检查所选语言之前或之后。在实际重定向之前,使用这两个检查来确定要重定向到的链接。

元例子:

// We want all users to use the domain with www.
$redir = '';
if (substr ($url, 0, 3)) != 'www') {
    $redir .= 'www.';
}

// If user has selected a different language, we need to redirect for that too.
if (!empty ($lang)) {
    $redir .= "{$base_url}/{$lang}/";
}

// If $redir isn't empty, redirect the user.
// PS: Always remember to use `die()` after a `header()` redirect!