【问题标题】:Content files are not working when URL rewrite using htaccess使用 htaccess 重写 URL 时内容文件不起作用
【发布时间】:2014-01-12 19:25:33
【问题描述】:

当有人调用 example.com/page/3fssdfs 之类的 url 时,我希望进行 URL 重定向,这将类似于 page?id=3fssdfs 为此我使用了以下 htaccess 代码。

RewriteRule ^page/([A-Za-z0-9-]+)/?$ page.php?id=$1

因此,当有人访问 example.com/page/3fssdfs 时,页面加载正常。但是 CSS 和图像文件不会加载。当我检查控制台时,它们看起来像这样,

GET http://example.com/page/assets/css/index.css 404 (Not Found)

css 文件的存储方式类似于 example.com/assets

那么我该如何解决这个错误呢?谢谢

这里是完整的 .htaccess 文件

RewriteEngine on
RewriteBase /

#if the file does NOT exist (! means NOT, and -f means file exists)
RewriteCond %{REQUEST_FILENAME} !-f
#if the directory does NOT exit (-d stands for directory exists)
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^page/([A-Za-z0-9-]+)/?$ page.php?id=$1

RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^([^\.]+)$ $1.php [NC]

RewriteCond %{REQUEST_FILENAME}.html -f 
RewriteRule ^([^\.]+)$ $1.html [NC]'

【问题讨论】:

  • 你想做什么? page/assets/css/index.css 不应该是 /assets/css/index.css 吗?或者你想得到类似?page=/assets/css/index.css
  • @Gasim css 文件位于根文件夹中,在 URL 重写编辑后,url 看起来像 example.com/page/123 并且服务器认为 CSS 文件在 page/css/ 内而不是在根文件夹中
  • @Gasim 简单地说,我需要加载 css 文件,css 文件未加载,因为页面认为 css 文件位于名为 page 的不同文件夹中,但事实并非如此。页面只是一个url重写路径。
  • 抱歉,我误解了这个问题。我不知道您如何处理文件,但您需要将文件设为“绝对路径”。就像不是“assets/css/index.css”,它应该是“/assets/css/index.css”。编辑:或基本标签http://www.w3schools.com/tags/tag_base.asp
  • @Gasim 谢谢它的工作:)

标签: php regex apache .htaccess mod-rewrite


【解决方案1】:

添加重写条件:

#if the file does NOT exist (! means NOT, and -f means file exists)
RewriteCond %{REQUEST_FILENAME} !-f
#if the directory does NOT exit (-d stands for directory exists)
RewriteCond %{REQUEST_FILENAME} !-d`

就在你的重写规则之前。

如果以上两个都成立,你的规则就会被改写;如果没有,则不会进行任何重写,您将能够访问内容文件。

【讨论】:

  • 恐怕问题还是一样。这是完整的 .htaccess 文件
猜你喜欢
  • 1970-01-01
  • 2015-04-15
  • 2015-02-03
  • 2014-08-08
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多