【问题标题】:How to redirect root to subdirectory using .htaccess如何使用 .htaccess 将根目录重定向到子目录
【发布时间】:2023-04-10 19:35:01
【问题描述】:

我目前正在使用共享主机,无法将我的文件放在“public_html”文件夹之外。

要解决此问题,我想使用 .htaccess 文件中的以下脚本将我的“根”站点重写为子目录:

RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/subdir/
RewriteRule ^(.*)$ /subdir/$1

这很好用,除非我导航到 www.example.com/subdir/。该 url 不会重定向到任何地方,它只是显示子目录。这是相对 url 等的问题。

有没有办法继续将我的根目录重写为子目录,同时将 www.example.com/subdir/ 重写为 www.example.com

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite redirect


    【解决方案1】:

    您可以在 root .htaccess 中使用此规则:

    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
    RewriteCond %{REQUEST_URI} !^/subdir/ [NC]
    RewriteRule ^(.*)$ subdir/$1 [L]
    

    并在/subdir/.htaccess中使用此规则:

    RewriteEngine On
    RewriteBase /subdir/
    
    RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
    RewriteCond %{THE_REQUEST} /subdir/(\S*)\s
    RewriteRule ^ /%1? [R=302,L,NE]
    

    【讨论】:

    • 根据我的测试,您也可以在根 .htaccess 中使用它。关键是 THE_REQUEST
    • 是的,这是真的,只要/subdir/.htaccess 不存在,它就可以在root .htaccess 中完成。
    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 2017-06-26
    • 2010-11-02
    相关资源
    最近更新 更多