htaccess 301重定向到语言子目录

时间:2014-11-08 14:50:32

标签: php apache .htaccess mod-rewrite redirect

我更改网站网址以接受不同的语言,因此,我将网站内容移至默认语言

从:www.site.com到:www.site.com/en

现在,我正在从php进行重定向,如果$_GET['lang']不存在或$_GET['path']存在,请重定向到site.com/en或site.com/en/(path)但我认为301从根目录重定向到文件夹更好。

我该如何写这条规则?

这是我的htaccess文件:

RewriteEngine on
RewriteBase /

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

RewriteRule ^download/(.*)$ php/download.php?id=$1 [L]

# with language
RewriteRule ^([a-z]{2})/p/(.*)$ single.php?lang=$1&hash=$2 [L]
RewriteRule ^([a-z]{2})$ index.php?lang=$1 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$ index.php?path=$1 [NC,L,QSA]

由于

1 个答案:

答案 0 :(得分:0)

如果我的理解是正确的,那就可以做你想要的。

Updated .htaccess (提供更好理解的评论)

RewriteEngine on
RewriteBase /

# If the hostname is a `www` subdomain, redirect to the parent domain
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# Internal rewrite of Download request URL to download PHP script
RewriteRule ^download/(.*)$ php/download.php?id=$1 [L]

# If request path is just root `/` (redirect to default language site)
RewriteRule ^$  /en [R=301,L]

# If request path is a language code,
# internally rewrite to index.php with `lang` query paramater
RewriteRule ^([a-z]{2})$ index.php?lang=$1 [L,NC,QSA]

# If request path begins with lang code and has a hash segment,
# internally rewrite to single.php with `lang` and `hash` query parameters
RewriteRule ^([a-z]{2})/p/(.*)$ single.php?lang=$1&hash=$2 [L]

# If request path begins with lang code and has additional segements
RewriteRule ^([a-z]{2})/(.*)$ index.php?lang=$1&path=$2 [NC,L,QSA]

# For every other request path not having a language code,
# if path is not an existing file or directory,
# redirect to a path prefixing default lang code before the requested path
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$  /en/$1 [NC,L,R=301]