【问题标题】:.htaccess to hide index.php with relative link issue.htaccess 隐藏带有相对链接问题的 index.php
【发布时间】:2012-07-13 20:37:17
【问题描述】:

这些天我正在尝试使用 CodeIgniter。

默认情况下,它在 URI 中有 index.php,如下所示

http://www.example.com/index.php/home

home 是控制器内部的一个函数

但我不想要 index.php,所以我创建了 .htaccess 文件:

Allow from all
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond $1 !^(index\.php|img|robots\.txt|script|css)
RewriteRule ^(.*)$ index.php/$1 [L]

基本上它会自动添加“index.php”,除非条件匹配。

但是事情是这样的:
对于这样的 URI:http://www.example.com/home
一切正常。

对于这样的 URI:http://www.example.com/home/
然后我网页中的相关链接变得疯狂。
例如: css/common.css 被重定向到 index.php/home/css/common.css 导致找不到 css 文件。

日志是这样的:

strip per-dir prefix: [dir to my site]/home/css/common.css -> home/css/common.css
applying pattern '^(.*)$' to uri 'home/css/common.css'
rewrite 'home/css/common.css' -> 'index.php/home/css/common.css'
add per-dir prefix: index.php/home/css/common.css -> [dir to my site]/index.php/home/css/common.css
trying to replace prefix [dir to my site]/ with /
internal redirect with /index.php/home/css/common.css [INTERNAL REDIRECT]
add path info postfix: [dir to my site]/index.php -> [dir to my site]/index.php/home/css/common.css
strip per-dir prefix: [dir to my site]/index.php/home/css/common.css -> index.php/home/css/common.css
applying pattern '^(.*)$' to uri 'index.php/home/css/common.css'
pass through [dir to my site]/index.php

我该如何解决这个问题?

【问题讨论】:

    标签: html apache .htaccess codeigniter


    【解决方案1】:

    这里的问题不是你的重写规则——它们很好。发生的事情是浏览器认为/home/末尾带有斜线是一个真实目录,因此它会将所有相对链接添加到它认为它所在的目录的前缀。然后浏览器会冲掉对CSS文件的请求,路径为@ 987654322@,自然会被重写,因为它与您的支票不符。

    我在这里看到的最快的解决方案是对 CSS 文件使用绝对路径。只需将它们链接为 /css/common.css 而不是您现在拥有的相对链接。

    【讨论】:

    • 其实我在我的网站上使用了很多这样的链接。只要所有链接都是从我的页面生成的,它们就可以了。那么我可以忽略这个问题吗?
    • 不知道能不能无视——如果找不到CSS文件,不影响渲染吗?
    • 是的,但只要链接是由我的页面生成的,它们就不会包含最后一个斜杠并且看起来工作正常
    • 哦,是的,在这种情况下,你应该没问题。但这是一个脆弱的解决方案 :) 如果您忘记了某个页面,或者其他人链接到您的页面并添加了斜杠怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多