【问题标题】:Approach to minimize dir-hardcoding in a RewriteRule that works from root and subfolder在根目录和子文件夹工作的 RewriteRule 中最小化目录硬编码的方法
【发布时间】:2012-02-07 12:24:55
【问题描述】:

我有这个项目,我从网络服务器的根目录本地运行。这是一个学校项目,因此它将被部署到我学校的服务器上,这需要我将它放在一个子文件夹中。这会导致静态 + css 重定向出现问题,因为当从子文件夹运行时,它显然无法按照现在的写入方式工作,而且我不想将每个重写规则硬编码到子文件夹,因为这很难看,并且如果需要,很难切换到从 root 运行它。

该项目在 .htaccess 中有以下规则。

Options +FollowSymlinks
RewriteEngine On

RewriteCond %{THE_REQUEST} ^GET\ /static/
RewriteRule ^static/(.*) /$1 [L,R=301]
RewriteCond %{THE_REQUEST} ^GET\ /css/
RewriteRule ^css/(.*)$ static/css/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

是否有一种方法可以让我在根目录和子文件夹中都进行上述重写而无需提出任何问题,或者有一种方法可以使差异最小化? (我不需要在每个规则中对子文件夹进行硬编码)

【问题讨论】:

    标签: .htaccess redirect root subdirectory


    【解决方案1】:

    我看到它的方式(假设 .haccess 也在子文件夹中)

    Options +FollowSymlinks
    RewriteEngine On
    
    #you might need a rewritebase, but not necessarily 
    #testing
    #RewriteBase /
    #production
    #RewriteBase /subfolder
    
    #less strict condition. will only be a problem if there is another folder also named 'static' inside 'static' :-)
    RewriteCond %{THE_REQUEST} /static/
    RewriteRule ^static/(.*) $1 [L,R=301]
    
    #condition here is not needed
    RewriteRule ^css/(.*)$ static/css/$1 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
    

    【讨论】:

    • 这是完美的,甚至更好:如果我省略了一个 RewriteBase,如果我单独部署到根目录或子文件夹,它都可以工作!非常感谢您的解决方案。
    猜你喜欢
    • 2015-04-06
    • 2015-12-11
    • 1970-01-01
    • 2012-02-20
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2012-09-22
    相关资源
    最近更新 更多