.htaccess重定向,css/图像不再加载



我有一个简单的HTML项目,位于一个名为"buddies"的文件夹中的托管帐户上,其完整URL看起来像这样 http://www.example.com/buddies/

我正在尝试重写 URL 以指向这样的 PHP 文件;

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ((?:css|images|js)/.*)$ /$1 [L]
# About Us
RewriteRule ^about_us/what_we_do/?$ about-what-we-do.php [NC,L]
RewriteRule ^about_us/mission/?$ about-our-mission.php [NC,L]
RewriteRule ^about_us/team/?$ about-team.php [NC,L]
RewriteRule ^about_us/what_next/?$ about-what-next.php [NC,L]
# Classes
RewriteRule ^classes/learn/?$ classes-learn.php [NC,L]
RewriteRule ^classes/1to1/?$ classes-one-to-one.php [NC,L]
RewriteRule ^classes/swim_fit/?$ class-swim-fit.php [NC,L]
# Information
RewriteRule ^information/timetable/?$ info-timetable.php [NC,L]
RewriteRule ^information/contact/?$ info-contact.php [NC,L]
RewriteRule ^information/location/?$ info-locations.php [NC,L]

这在重定向到正确的 PHP 文件的 URL 时效果很好,但是这样做会破坏指向所有图像和 css 文件的链接。我明白为什么这样做,css 和图像文件夹在路径"about_us/what_we_do/"中不存在

如果这是在域的根目录中运行的,我只需在所有图像/css 文件的前面加上一个"/",即"/css/style.css",而不是它们当前引用的方式"css/style.css"。

有人可以建议一种我仍然可以从"css","images"和"js"文件夹中服务器css,图像和javascript的方法吗?我不必在每个 css/图像引用前面附加"好友"文件夹。

编辑:我像这样引用样式表;

<!-- Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/style-768.css">
<link rel="stylesheet" type="text/css" href="css/style-992.css">

如果所有 CSS 文件都在目录/css中,您可以将每个文件重写到此目录

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (css/.*.css)$ /$1 [L]

如果请求是针对/css/...的,则RewriteCond是为了避免重写循环。

图像和Javascript文件类似。如果您只查看目录,您甚至可以将所有内容合并为一个规则

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ((?:css|images|js)/.*)$ /$1 [L]

这将查找以css/images/js/开头的任何请求。


如果CSS文件不是%{DOCUMENT_ROOT}/css而是%{DOCUMENT_ROOT}/buddies/css,则目标必须相应地添加前缀,例如

RewriteRule ((?:css|images|js)/.*)$ /buddies/$1 [L]

使用<base href="http://www.example.com/">,以便将外部文件重定向到该目录。

最新更新