【问题标题】:htaccess pretty URL shows no css or images in PHP MVChtaccess 漂亮的 URL 在 PHP MVC 中没有显示 css 或图像
【发布时间】:2016-01-01 19:49:34
【问题描述】:

第一次使用 htaccess 创建一个漂亮的 url 项目以及一个简单的 PHP 项目结构。我得到了关于 OK-ish 的漂亮 url,我现在唯一的问题是我的 CSS/media/... 没有加载到页面上。

这是我使用的 htaccess 代码:

RewriteEngine on

# localhost
RewriteBase /project/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?p=$1
RewriteRule ^(.*)/(.*)$ index.php?p=$1&id=$2

# fix trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [R=301,L]

所有内容都需要路由到 index.php 文件,我的一般模式如下所示:

.com/desktops
.com/laptops
.com/desktop/Intel-Core-i5-Gaming
.com/laptop/Intel-Core-i5-Gaming

我希望你们中的某个人能在这方面教我一些智慧! :)

【问题讨论】:

  • 你需要告诉apache不要通过排除它们来路由css、字体和其他,你可以做类似RewriteRule !\.(js|gif|jpg|png|css|woff|woff2|ttf|eot|svg)$
  • @adelowo 他只重写那些不存在的。

标签: php css .htaccess url-routing


【解决方案1】:

这应该可行。

RewriteCond ${REQUEST_URI} ^.+$
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|png|js|css|swf|php|ico|txt|pdf|xml)$ [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

或者有 3 种不同的方法来解决这个问题:

对图像、css 和 js 文件使用绝对路径,即以 / 或 http:// 开始您的路径

另一种是在 HTML 头部中使用 base href 标记,如下所示:

<base href="http://www.example.com/">

第三个选项是通过 mod_rewrite

将这些行放在 .htaccess 文件中的其他 RewriteLine 上方:

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]

【讨论】:

  • 这适用于 1 个参数,当添加第二个参数时,它会恢复为无 css/media/...
  • 使用&lt;base href="http://www.example.com/"&gt; 解决了我的问题。我不确定我应该把你在 htaccess 中写的最后几行放在哪里。如果我只在 htaccess 中解决这个问题,你能告诉我把这些放在哪里吗?
  • @Nerdben 检查我的答案。我先给了同样的东西。我知道这个问题。
【解决方案2】:

如果您添加了类似的 CSS:

<link rel="stylesheet" href="CSS/media/..." />

它不起作用,因为你的路由,它会去不同的地方,比如进入子域(实际上不存在)。所以考虑使用域的相对路径:

<link rel="stylesheet" href="/CSS/media/..." />
<!---------------------------^ add a slash here.

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 2010-11-01
    • 2012-05-07
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多