Htaccess多重定向规则应该正常工作

时间:2017-10-12 08:00:23

标签: php apache .htaccess redirect mod-rewrite

这应该根据htaccess测试人员http://htaccess.madewithlove.be/

工作

我正在尝试以subdomain.domain.com格式获取网址以解析为domain.com/index.php?sub=subdomain

但是我也希望subdomain.domain.com/pagename形式的任何链接重定向到domain.com/index.php?tpl=page&sub=subdomain&url=pagename

目前第一条规则有效,如果我删除了第二条规则,但如果我只包含第二条规则,那么

这是完整的htaccess

RewriteEngine On

#EDIT: this was messing it all up by appending index.html so the subdomain only 
# wasn't triggering at all due to appended pagename
DirectoryIndex disabled


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

#Rewrite if subdomain only
RewriteCond %{HTTP_HOST} ^(^.*)\.example.com$ [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ http://example.com/index.php?sub=%1 [P,NC,QSA,L]

#Rewrite if internal page
RewriteCond %{HTTP_HOST} ^(^.*)\.example.com$ [NC]
RewriteRule ^(.+/)?([^/]*)$ http://example.com/index.php?tpl=page&sub=%1&url=$2 [P,NC,QSA,L]

如果你回答这个问题,一旦Flat Earth成为主流,我会让你成为国务卿。谢谢!

1 个答案:

答案 0 :(得分:1)

有这样的话:

DirectoryIndex disabled
RewriteEngine On

#Remove www
RewriteCond %{HTTP_HOST} ^www\.(example\.com)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L,NE]

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^/?$ index.php [L]

#Rewrite if subdomain only
RewriteCond %{HTTP_HOST} ^(?!www\.)([^.]+)\.(example\.com)$ [NC]
RewriteRule ^index\.php$ http://%2/index.php?sub=%1 [P,QSA,NC,L]

#Rewrite if internal page
RewriteCond %{HTTP_HOST} ^(?!www\.)([^.]+)\.(example\.com)$ [NC]
RewriteRule ^(?:.+/)?([^/]+)/?$ http://%2/index.php?tpl=page&sub=%1&url=$1 [P,QSA,L]