简体   繁体   中英

Problem with mod_rewrite not working correctly

I'm trying to pretty up the URL's on a website using mod_rewrite. But it doesn't seem to be working. I want the following URL:

http://mydomain.com/test

To be rewritten as:

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

My .htaccess file looks like this:

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

But it does not seem to be working.

mod_rewrite is definitely enabled because the following simple rule does redirect the site to example.com:

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

My site is hosted with GoDaddy if that makes a difference. The site is also setup as a subdomain of the main site.

Ok, looks like I need to specify the full URL in the rewrite rule:

<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>

It now displays the page correctly.

I use this snippet to get the everything of the path except some resource files which should'nt be parsed:

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

In main.php I call GetSegments() which will give me an array of the called path:

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;
}

Some examples:

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

Maybe this short code snippets are also useful for your work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM