【问题标题】:Htaccess multiple redirect rules should be workingHtaccess 多个重定向规则应该可以工作
【发布时间】:2017-10-12 08:00:22
【问题描述】:

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

我正在尝试获取格式为 subdomain.domain.com 的 url 以解析为 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 成为主流,我会让你成为国务卿。谢谢!

【问题讨论】:

    标签: php apache .htaccess redirect mod-rewrite


    【解决方案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]
    

    【讨论】:

    • 谢谢。我必须更改 url=$1 才能使页面名称在您的页面中工作,“仅子域”规则使用 htaccess 测试器可以正常工作,但我发现由于某种原因,服务器或浏览器总是将 index.html 作为页面名称附加,这使得它由于某种原因,总是认为有一个页面名称。我不知道如何防止这似乎是自动的。我发布的代码似乎也可以正常工作。
    • 我发现添加 DirectoryIndex disabled 解决了 index.html 被附加的问题。
    • DirectoryIndex disabled 会阻止主页,因此 www 重定向代码现在不起作用...我正在尝试弄清楚如何保持 directoryindex 禁用但没有将 index.html 附加到每个 url。我尝试了 options -indexes 但这在服务器上根本不起作用。我可能需要在 www 重定向中将用户显式发送到 domain.com/index.php。这会更改 url,因为它是 301,所以我可能需要单独执行此操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多