【问题标题】:CSS, JS and images do not display with pretty urlCSS、JS 和图像不显示漂亮的 url
【发布时间】:2015-02-28 22:18:03
【问题描述】:

我正在尝试通过 htaccess 文件重写 URL,以便以下 URL

www.domain.com/subfolder/index.php?key

可以通过以下方式访问:

www.domain.com/subfolder/index.php/key

指定的“键”将决定在 PHP 代码中包含哪个页面。 我已经有以下 htaccess 代码,但是在使用第二个(干净的)URL 时,没有显示 CSS、JS、图像等。关于可能是什么问题的任何想法?

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{DOCUMENT_ROOT}/$1 -f
RewriteRule ^[^/]+/([^.]+\.(?:js|css|jpe?g|png|gif))$ /$1 [L,R=301,NC]
RewriteRule ^index.php/([a-zA-Z0-9/_]+)$ index.php?key=$1

【问题讨论】:

  • 您必须对所有 html 资源(css、js、图像、href 链接等)使用绝对路径而不是相对路径跨度>
  • 感谢您的回答! webapp的位置可能会改变,改变所有路径会很痛苦,我正在寻找一个htaccess解决方案。
  • 你不能用 htaccess 处理它。您所能做的就是使用 absolute 路径。您可以通过在页面中的每个 <head> 之后添加一个标签来做到这一点:<base href="/path/to/website/">。在此处查看我对类似问题的回答:stackoverflow.com/questions/25630373/…
  • 谢谢贾斯汀。将其添加到头部并按预期工作!

标签: apache .htaccess url mod-rewrite redirect


【解决方案1】:

当您使用相对 url 时,浏览器将使用它加载的资源的 url 动态创建一个完整的 url。换句话说:它使用地址栏中显示的 url。在您的情况下(www.domain.com/subfolder/index.php/key),它会尝试加载相对于www.domain.com/subfolder/index.php/ 的任何相对 url。但是,您的资源不在那里。

您有两种选择来解决此问题:

  • 将您的相对 url 转换为绝对 url,至少对于域根目录是绝对的。像<img src="img/unicorn.png"> 这样的东西应该变成<img src="/path/to/img/unicorn.png">

  • 为您的头部元素添加一个基础。将使用此基数代替资源的 url 来计算完整的 url。您应该将 <base href="/"> 添加到您的 <head> 元素中。 / 将被用作任何相对 url 的基础。

【讨论】:

    【解决方案2】:

    您是否尝试过基本 URL?这是我遇到的最好的解决方案。只需将一个放在头部,然后您甚至可以给它一个 ID 并使用 javascript 访问 URL。

    <base id='baseElement' href="your path goes here">  <!--possibly generated with serverside code-->
    

    使用 jquery 访问

    var base = $('#baseElement').attr('href');
    

    【讨论】:

    • 任何关于如何实现这个想法的附加信息(代码示例、文档)都会改进这个答案。
    【解决方案3】:

    其实 .htaccess 有一个解决方案!

    假设您的 index.php 位于 /mysite/ 并且您的资源文件位于 /mysite/scripts//mysite/images//mysite/style/ 中,就像地雷一样,您可以这样:

    RewriteEngine on
    #first exclude those folders
    RewriteBase "/mysite/"
    RewriteRule ^(style|scripts|images)($|/) - [L]
    #then go with your rules (the [L] terminates the ruling)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteCond %{DOCUMENT_ROOT}/$1 -f
    RewriteRule ^[^/]+/([^.]+\.(?:js|css|jpe?g|png|gif))$ /$1 [L,R=301,NC]
    RewriteRule ^index.php/([a-zA-Z0-9/_]+)$ index.php?key=$1
    

    您可以通过其他几种方式查看.htaccess mod_rewrite - how to exclude directory from rewrite rule

    【讨论】:

      【解决方案4】:

      另外,您可以尝试将其添加到您的 HTaccess:

      RewriteBase /
      

      【讨论】:

      • 为什么会这样? RewriteBase 是用于重写的基础,但由于此问题与实际发生的重写无关,因此没有任何影响。
      猜你喜欢
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多