.htaccess - 针对3种不同的URL结构进行3次不同的重写

时间:2013-09-28 14:55:16

标签: regex apache .htaccess mod-rewrite

我正在尝试在我的博客门户网站上使用htaccess实现以下目标:

结构1

example.domain.com/link/sublink - > /blogdisplay.php?page=example&page2=link&page3=sublink

结构2

en.domain.com/link/sublink/subsublink - > /index.php?lang=en&page=link&page2=sublink&page3=subsublink

结构3

domain.com/link/sublink/subsublink - > /index.php?page=link&page2=sublink&page3=subsublink

我如何实现这一目标?这是我目前的代码(现在不处理语言,但其他两个URL结构工作正常):

RewriteEngine On

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

RewriteCond %{HTTP_HOST} !^www.[NC]
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9-]{3,})\.domain.com$ [NC]
RewriteRule ^$ blogdisplay.php?page=%1 [L,QSA]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.+?)\.domain\.com$ [NC]
RewriteRule ^([a-z0-9-]+)/?$ blogdisplay.php?page=%1&page2=$1 [L,QSA]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.+?)\.domain\.com$ [NC]
RewriteRule ^([a-z0-9-]+)/([a-zA-Z0-9-]+)/?$ blogdisplay.php?page=%1&page2=$1&page3=$2 [L,QSA]

## If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f
## don't do anything
RewriteRule ^ - [L]

RewriteRule ^([a-z0-9-]+)/?$ index.php?page=$1 [L,NC]
RewriteRule ^([a-z0-9-]+)/([a-zA-Z0-9-]+)/?$ index.php?page=$1&page2=$2 [L,NC]
RewriteRule ^([a-z0-9-]+)/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/?$ index.php?page=$1&page2=$2&page3=$3 [L,NC]

1 个答案:

答案 0 :(得分:2)

对于语言案例,您可以添加此附加案例(仅低于R = 301规则):

RewriteCond %{HTTP_HOST} ^([a-z]{2})\.domain\.com$ [NC]
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/?$ index.php?lang=%1&page=$1&page2=$2&page3=$3 [L,NC,QSA]

PS:另外,我建议将If the request is for a valid file规则移到上述语言规则之上。