【问题标题】:.htaccess: Redirect root url to subdirectory, but retain root url.htaccess:将根 url 重定向到子目录,但保留根 url
【发布时间】:2011-07-21 10:08:18
【问题描述】:

我正在清理我的域的目录结构(对我来说,在根目录中设置根 url 的内容真是太糟糕了!)并且需要一些关于如何正确使用 RewriteRule 的见解。

要点

我希望 domain.tld 使用 domain.tld/subdirectory/ 但仍然在 url 中显示为 domain.tld。 p>

我的 .htaccess 到目前为止

Options +FollowSymlinks
RewriteEngine On

#Force removal of wwww subdomain
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.domain.tld
RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]

#Trailing slash
RewriteRule ^/*(.+/)?([^.]*[^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]

#Redirect root url to subdirectory
RedirectMatch 301 ^/subdirectory/$ http://domain.tld/
RewriteRule ^/$ /subdirectory/?$ [L]

RedirectMatch 效果很好。不幸的是,那里的最后一个 RewriteRule 似乎应该工作得足够简单,但事实并非如此。根目录中的旧内容设置仍然出现。

我在这里错过了什么?

更新:已解决

简单的修复,我对 .htaccess / apache 经验不足,无法解释原因。

我有:

RewriteRule ^/$ /subdirectory/?$ [L]

删除一个斜线可以解决所有问题:

RewriteRule ^$ /subdirectory/?$ [L]

所以现在我的问题是:为什么会这样?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    试试这个:

    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{REQUEST_URI} !^/subdirectory/
    
    # REWRITES ALL URLS 
    # [REPLACE "domain" WITH THE ACTUAL DOMAIN, 
    # WITHOUT THE TLD (.com, .net, .biz, etc)]
    RewriteCond %{HTTP_HOST} ^(www\.)?domain\.
    
    # REWRITE ALL THOSE TO subdirectory
    RewriteRule ^(.*)$ /subdirectory/$1 [L]
    

    BR 螺旋体

    【讨论】:

      【解决方案2】:

      RewriteRule 中的 URI 部分不包含前面的斜杠。

      所以要匹配http://example.com/,你必须使用RewriteRule ^$,其中RewriteRule ^/$理论上会匹配http://example.com//(注意双斜杠)。

      附加:最后的?$ 没有任何意义,因为这会添加一个带有空参数$ 的查询字符串。

      你终于有了:RewriteRule ^$ /subdirectory/ [L,QSA]

      【讨论】:

        【解决方案3】:

        两个规则都是有效

        这个用于服务器配置或虚拟主机上下文URL 以斜杠开头):

        RewriteRule ^/$ /subdirectory/ [L]
        

        如果您在 .htaccess 中放置相同的规则,那么您必须删除前导斜杠(因为它是相对于当前文件夹):

        RewriteRule ^$ /subdirectory/ [L]
        

        附言 Floern 已经提到了 ?$ 它的目标 URL 部分。根本不需要$。如果您使用? 完成您的 URL,这会告诉 Apache 不要将查询字符串转移到新 URL(完全删除查询字符串)。

        此外,[QSA] 标志仅在您使用查询字符串进行操作(在目标 URL 中有 ?)并且仍然希望将当前查询字符串附加到新构建的 URL 时才需要。这意味着在这条规则中 RewriteRule ^$ /subdirectory/ [L,QSA] [QSA] 标志什么都不做,可以安全地删除。

        【讨论】:

          【解决方案4】:

          我尝试了解决方案,但在我的情况下删除了 /folder/ 但显示旧网站 (www.site.it) 而不是 www.site.it/folder/ 删除了“文件夹”...我复制并粘贴了相同的代码,但在我的情况下不起作用:(我打开了一个新主题:.htaccess: Redirect root wordpress url to another wordpress in a subdirectory, but retain root url

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-03-14
            • 2016-06-27
            • 1970-01-01
            • 2010-11-02
            • 2020-01-08
            • 1970-01-01
            • 2017-06-05
            • 2012-06-03
            相关资源
            最近更新 更多