将网站重定向到内部链接


Redirect website to inner links

我有一个多语言网站,这种结构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/

我怎样才能做到只有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中写什么来为每种语言工作呢?因为如果我将rewriterrule更改为url.com/en/,其他语言就不再工作了。

如何实现这一点取决于您从哪里获得语言字符串,您希望支持多少种语言,以及这种交互应该有多复杂。

如果只是几种语言,你想使用浏览器设置,你可以使用htaccess重写。

然而,如果你有不止几种语言,想让用户在网站本身选择他们自己的语言,或者比上面更复杂的东西。那么,你需要在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!