【问题标题】:mod_rewrite - I can't make it to work like I wantmod_rewrite - 我不能让它像我想要的那样工作
【发布时间】:2012-05-31 18:55:27
【问题描述】:

感谢阅读。首先,我在根目录中有一个 .htaccess,其中包含以下语句:

# Mod Rewrite
<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteRule     ^$              /root/              [L]
    RewriteRule     (.*)            /root/$1            [L]
</IfModule>

在根文件夹中我得到了这个文件:

# Mod Rewrite
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$          /root/index.php/$1 [PT,L]
</IfModule>

另外,在文件夹 /root 中,我有三个文件夹:cssjsimages

我的应用程序被设计为与我的 MVC 框架分离(有点像 CodeGgniter)。所以这是树:

- application
    - my application files are there
- root
    - css
    - js
    - images
- grecko
    - my mvc framework files are there

这样,我可以更新我的框架,而无需触及在应用程序文件夹下运行的整个网站。

不管怎样,我现在想做的就是把我上面说的三个文件夹(cssjsimages)移动到/application/assets/里面。但由于所有内容都被重定向到/root/,我需要一个规则,允许将http://www.domain.tld/css/blabla.css 之类的请求映射到/application/assets/css/blabla.css 等。

我尝试过,但没有成功。

谢谢。

【问题讨论】:

    标签: php model-view-controller .htaccess apache2


    【解决方案1】:

    将此代码放入$DOCUMENT_ROOT/.htaccess:

    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteBase /
    
        RewriteRule ^(css|js|images)(/.*|)$ application/assets/$1$2 [L,NC]
    
        RewriteCond %{ENV:REDIRECT_STATUS} !200
        RewriteRule ^ root${REQUEST_URI} [L]
    </IfModule>
    

    【讨论】:

    • 完美运行!但是因为你写得太快了嘿嘿,有一个错误所以我以这行结尾:RewriteCond %{ENV:REDIRECT_STATUS} !200RewriteRule (.*) root/$1 [L]
    • 很高兴知道它对您有用。 %{ENV:REDIRECT_STATUS} !200 实际上是确保内部重定向只应用一次。对你来说发生了什么,两个规则都被一个接一个地应用。正如您在 RewriteLog 中看到的那样,您提供了:rewrite 'application/assets/css/global.css' -&gt; 'root/application/assets/css/global.css' 正在发生,它将所有内容发送到 root/
    • 忘了补充%{ENV:REDIRECT_STATUS}是mod_rewrite模块使用的内部变量,第一次内部重定向成功后设置为200。
    • 好的,谢谢!我知道这是为了什么,但不知道申请这里的原因......这是一个非常好的技巧。感谢您的信息
    【解决方案2】:

    尝试将它放在您的网络根目录(不是根文件夹)的 .htaccess 中:

    RewriteEngine on
    
    RewriteRule ^(css|js|images)(.*) application/assets/$1$2 [L]
    
    RewriteCond %{REQUEST_URI} !^/application/assets [NC]
    RewriteRule (.*) root/$1 [L]
    

    避免多余的空格。

    【讨论】:

    • 不起作用。它什么也不做。我什至在我的根文件夹中尝试过。他将它发送到 /root/index.php/$1 并且他认为 cssimagejs 是控制器,因此它显然不起作用。谢谢!
    • 这应该在它进入 root 或 root/index.php 之前被捕获 - 你能发布完整的文件吗?
    • 您在上面看到的是完整的 .htaccess 文件。我知道这很奇怪,就像我说我确实尝试过但我无法让它工作,因为它“什么都不做”,因为我的 MVC 认为我想要 CSS 控制器或图像。
    • 我的意思是在你添加我的规则后发布完整的文件。
    • /application 中是否还有另一个 .htaccess?你能在 VirtualHost 配置中添加一些 RewriteLog 规则吗?
    猜你喜欢
    • 1970-01-01
    • 2015-05-16
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多