htaccess 漂亮 URL 不显示 css 或 PHP MVC 中的图像

htaccess pretty URL shows no css or images in PHP MVC

第一次使用 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=
RewriteRule ^(.*)/(.*)$ index.php?p=&id=

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

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

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

希望大家能教教我这方面的智慧! :)

如果您添加了您的 CSS 赞:

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

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

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

这应该有效。

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 头部部分使用基本 href 标签,如下所示:

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

第三个选项是通过 mod_rewrite

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{DOCUMENT_ROOT}/ -f
RewriteRule ^[^/]+/([^.]+\.(?:js|css|jpe?g|png|gif))$ / [L,R=301,NC]