【问题标题】:Style not applied when using htaccess使用 htaccess 时未应用样式
【发布时间】:2011-07-16 08:06:18
【问题描述】:



我想根据所选国家/地区显示 url,因此我使用 htaccess 根据所选国家/地区重定向 url。例如,我希望 url 是这样的:www.example.com/us/index.html

我的文件如下所示,

public_html/includes/style.css  
public_html/index.php  

在 index.php 中,我将样式表链接为“../includes/style.css

当我尝试www.example.com 时,样式应用正确。一旦用户在 index.php 中选择了国家,url 将被重定向为www.example.com/us/index.html。但是对于这个重定向的页面,样式没有正确应用。

我在 .htaccess 中有以下条件来重定向页面,

RewriteRule ^([^/]+)/([^\.]+)\.html$ index.php?cnt=$1 [L]  

谢谢。

【问题讨论】:

    标签: php css .htaccess redirect


    【解决方案1】:

    访问 www.example.com/us/index.html 时,style.css 计算的 url 是 www.example.com/us/includes/style.css 显然不存在。

    所以,根据你的意图,要么

    • 为样式表使用绝对链接,例如“/includes/style.css”
    • 创建一个 htaccess 重写规则来修复 url
    • 为每个国家/地区创建 1 个样式表

    【讨论】:

      【解决方案2】:

      如果您包含带有相对路径的 CSS 文件,则当您的 URL 超出初始主目录(或使用 .htaccess 时似乎移出)时,您的 CSS 将返回 404

      解决方案是在包含 css 时使用绝对路径

      而不是../includes/style.css

      使用<?php echo $webroot; ?>/includes/style.css

      $webroot 这里是您项目的 webroot 的完整路径

      【讨论】:

      • 谢谢。我也使用过相同的方法,在标题中我有一个变量 $home,它包含 $home="../" 之类的路径。在链接样式表时,我使用了 href="" 。对吗?
      • 不。 $home 仍然是一个相对路径。您需要获取域的基本 URL。如果您使用的是虚拟主机,您可以简单地使用/includes/style.css,但如果您使用的是localhost/project1 之类的东西,那么您必须弄清楚您的webroot 在您的index.php 中是什么。你有什么样的设置?
      • 你是对的。出于测试目的,我将文件放在“localhost/projects/sample/”下。示例文件夹包含诸如 include/style.css 之类的目录和诸如 index.php、.htaccess 之类的文件。是否有任何特定的函数可以在 php 中获取 baseurl?
      • 好吧,如果您的 index.php 文件在 /sample 内,并且所有请求都到达该文件并且您的 css 文件在 /sample/includes/ 中,那么您可以使用 dirname(__FILE__) 获取当前目录然后将/includes 附加到它。如果您使用的是框架,则容易得多。 PHP 链接:php.net/manual/en/function.dirname.php
      【解决方案3】:

      应该是/includes/style.css,而不是../includes/style.css,仅此而已。
      始终使用绝对路径。

      【讨论】:

        【解决方案4】:


        感谢你的帮助。这是我用来解决问题的代码:

        $base = $_SERVER['REQUEST_URI'];  
        $base=parse_url($base);  
        $parts=explode("/",$base['path']);  
        $path=$parts[1];  
        $home="/".$path;  
        
        <link rel='stylesheet' type='text/css' href='$home/includes/style.css'/>
        

        但是,只有当我在 localhost 中运行它时它才对我有用,因为我将文件放在 home/localhost/example/
        但是当我把它放在服务器上时,我又遇到了风格问题。所以我只是像这样更改了 home 变量:

        $home="";
        

        所以现在路径变成了,

        /includes/style.css 
        

        而不是

        //includes/style.css
        

        【讨论】:

          猜你喜欢
          • 2013-10-21
          • 1970-01-01
          • 2019-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-20
          • 2017-04-22
          • 2018-02-28
          相关资源
          最近更新 更多