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 d开发者_如何学Goefinitely 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...
精彩评论