【问题标题】:Problem with mod_rewrite not working correctlymod_rewrite 无法正常工作的问题
【发布时间】:2011-06-28 21:27:01
【问题描述】:

我正在尝试使用 mod_rewrite 来美化网站上的 URL。但这似乎不起作用。我想要以下网址:

http://mydomain.com/test

改写为:

http://mydomain.com/index.php?t=test

我的 .htaccess 文件如下所示:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On  
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?t=$1 [L]
</IfModule>

但它似乎不起作用。

mod_rewrite 肯定是启用的,因为以下简单规则确实会将站点重定向到 example.com:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On  
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ http://example.com/?
</IfModule>

我的网站由 GoDaddy 托管,如果这有所作为的话。该站点还设置为主站点的子域。

【问题讨论】:

  • 解释一下But it does not seem to be working.是什么意思@到底发生了什么?
  • 如果你把那些RewriteConds 拿出来怎么办?有必要吗?
  • RewriteConds 是必要的,在这种情况下它不会重写现有文件/文件夹

标签: php apache mod-rewrite friendly-url


【解决方案1】:

我使用这个 sn-p 来获取路径中的所有内容,除了一些不应该被解析的资源文件:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.(js|ico|gif|jpg|png|css)$ main.php

在 main.php 中,我调用 GetSegments(),它将给我一个被调用路径的数组:

function CheckSegmentsEmpty($var) {
    if($var == '') {
        return false;
    }
    else {
        return true;
    }
}

function GetSegments() {
    $path = dirname($_SERVER['SCRIPT_NAME']);
    if($path != '' && $path != '/')
        $segments = str_replace($path, '', $_SERVER['REQUEST_URI']);
    else
        $segments = $_SERVER['REQUEST_URI'];

    if($segments[0] == '/')
        $segments = substr($segments, 1);

    //$segments = strtolower($segments);
    $segments = preg_replace("!\.htm(l|l\?)$!si", '', $segments);

    $segments = explode('/', $segments);
    $segments = array_filter($segments, 'CheckSegmentsEmpty');

    return $segments;
}

一些例子:

  • http://www.domain.tld -> array()
  • http://www.domain.tld/test.html -> 数组('test')
  • http://www.domain.tld/test -> 数组('test')
  • http://www.domain.tld/a/b/c/d/e.xyz -> 数组('a', 'b', 'c', 'd', 'e.xyz')

也许这个短代码sn-ps对你的工作也有用...

【讨论】:

  • 谢谢!肯定会将此添加到我的 sn-ps 集合中。
【解决方案2】:

好的,看来我需要在重写规则中指定完整的 URL:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On  
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteRule ^(.*)$ http://mydomain.com/index.php?t=$1
</IfModule>

它现在可以正确显示页面了。

【讨论】:

  • 通常你不需要,你试过 /index.php 吗?
猜你喜欢
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 2012-08-05
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多