0

I've come to a point where I think I'm not allowed to understand how mod_rewrite works. In theory I think I got it, but just can't seem to make this work. I have the following file structure:

code
    -application/
    -bundles/
    -laravel/
    -public/
        -css/
        -js/
        -img/
        -index.php
    -storage/
    -.htaccess

Sadly, my httpd.conf VHost configuration has this:

<Directory path/to/code>
Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

DocumentRoot path/to/code

<IfModule dir_module>
DirectoryIndex index.php
</IfModule>

And I can't modify it to point to code/public/ so I think I could fix it with .htaccess. Now I've tried everything. Basically what I want to do is convert every request into /public/index.php/($1), except css, js, img which should be converted to:

/public/css/($1)
/public/img/($1)
/public/js/($1)

So if I have example.com/ this will change to example.com/public/index.php and their css, img, js etc would change to example.com/public/css, img, js.

I just can't do it :(

My .htaccess has taken many forms, recently I gave up everything and just look like this:

<IfModule rewrite_module>
    RewriteEngine on
    RewriteRule ^(.*)$ /public/index.php/$1
</IfModule>

This of course, give me 500 Internal Server Error because it causes loops in the rewriting (is not that clear to me anyways, but still)

So, my idea with .htaccess was (pseudocode):

<IfModule rewrite_module>
    RewriteEngine on

    RewriteCond %{REQUEST_URI} ^/css
    RewriteRule ^css/(.*)$ /public/css/$1

    RewriteCond %{REQUEST_URI} ^/img
    RewriteRule ^img/(.*)$ /public/img/$1

    RewriteCond %{REQUEST_URI} ^/js
    RewriteRule ^js/(.*)$ /public/js/$1

    RewriteRule ^(.*)$ /public/index.php/$1
</IfModule>

Any idea how can I accomplish this? I would like to understand a little what am I doing wrong. I'll love to figure out how to write good mod_rewrite .htaccess files.

I'm on Windows 7, Apache2.2

Thanks in advance.

4

1 回答 1

1

你会得到一个无限循环,因为每个重写的路径仍然必须从顶部返回通过 httpd.conf 和 .htaccess 指令。通常建议使用该L标志,但这只是告诉 Apache 停止当前运行;它不会阻止完成的重写路径必须从顶部通过指令。

如果要重写为“/public”,则需要添加一个 RewriteCond 以检查此重写是否尚未完成,否则每次都会发生重写并发生无限循环。

这应该适用于“公共”重写:

RewriteCond %{REQUEST_URI} !^/public/
RewriteRule (.*) /public/$1

这表示“如果请求的路径尚未开始,/public/则默默地重写请求以添加/public/到它前面。

目前还不清楚您要对外围文件请求(CSS、图像等)做什么。如果您想请求/public/page.css成为,/public/css/page.css那么应该执行以下操作:

RewriteRule ^public/([^/]+)\.css$ /public/css/$1.css

但是,我没有看到这样做的好处。我认为最好更新您的页面脚本或静态 HTML 页面,然后简单地更改它们以反映您想要用于 CSS 和图像文件的新路径结构。使用 mod_rewrite 来避免更新页面中的路径是一个坏主意(以我的拙见),并且会导致服务器负载更重和请求响应更慢。

如果您想了解有关 mod_rewrite 的更多详细信息,请参阅Apache mod_rewrite 手册页

于 2013-06-30T16:49:58.393 回答