【问题标题】:Mod-rewrite - how to make this rule work?Mod-rewrite - 如何使这个规则起作用?
【发布时间】:2013-11-28 20:52:35
【问题描述】:

我的网站有一个可以调用的文件 (index.php),使用控制器我可以显示不同的页面。此页面位于 office/web 中。

我通过以下方式修改了我的 .htaccess:

Options +FollowSymlinks
RewriteEngine On    # Turn on the rewriting engine

#skip existing files or directories
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#everything else goes to index.php
RewriteRule    ^sale/chicago/?$    /office/web/index.php?action=w_filter&type=1&zone=3    [NC,L]
RewriteRule    ^sale/?$    /office/web/index.php?action=w_filter&type=1    [NC,L]
RewriteRule    ^rent/?$    /office/web/index.php?action=w_filter&type=2    [NC,L]

访问http://localhost/office/web/sale/chicago/时,页面加载,所以主要规则起作用。

但是,所需的所有其他文件(css、js...)都给出了 404 Not found 错误。

在html文件中使用<script type='text/javascript' src='assets/js/bootstrap.min.js'></script>,它期望

http://localhost/office/web/sale/chicago/assets/js/bootstrap.min.js

正确的网址是:

http://localhost/office/web/assets/js/bootstrap.min.js

等等,对于所有其他媒体文件。

我需要在 .htaccess 中添加/更改什么来解决这个问题?

【问题讨论】:

    标签: php .htaccess mod-rewrite


    【解决方案1】:

    你应该使用绝对url来链接js和css。

    代替

    <script type='text/javascript' src='assets/js/bootstrap.min.js'></script>
    

    试试这个

    <script type='text/javascript' src='/office/web/assets/js/bootstrap.min.js'></script>
    

    如果有用请告诉我。

    【讨论】:

    • 是的,这项工作。我已经在考虑了。但是这样一来,每次上传服务器上的文件,都需要更改绝对路径。这是因为这些文件实际上是 html 模板......我更多地考虑了 .htaccess 解决方案。最终,我将不得不使用它。
    • @Parkyprg 为什么要更改绝对路径?
    • 因为在本地主机上我有 /office/web/,但在服务器上我有不同的文件路径(例如 /web/ only)
    • @Parkyprg 我曾经遇到过这个问题。然后我学会了在localhost中创建一个子域,例如myweb.localhost.com,它指向/office,所以和服务器中的一样。。
    【解决方案2】:

    这是纯基于mod_rewrite 的解决方案,您可以避免在资源(js、图像、图像等)中写入完整路径:

    将此规则添加到其他规则之上:

    RewriteRule ^(assets/.+?)$ /office/web/$1 [L,NC,R]
    

    另外请理解RewriteCond 仅适用于下一个RewriteRule。在您的问题中,您有 2 RewriteCond 仅适用于第一条规则,但接下来的 2 条规则没有。

    作为为每个规则添加RewriteCond 的替代方法,您可以将此规则放在顶部 以跳过所有文件/目录的重写规则:

    ## If the request is for a valid directory
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    ## If the request is for a valid file
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    ## don't do anything
    RewriteRule ^ - [L]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多