0

I'm trying to rewrite the following URL

www.domain.com/category.php?id=13

to:

www.domain.com/category/cat-name

I've followed some .htaccess tutorials but I couldn't. How can I make it work?

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
user3012008
  • 29
  • 1
  • 5
  • You followed tutorials but you coudnt? – Mihai Mar 22 '14 at 10:24
  • This sounds like "I did nothing and expect you to do it for me." What did you try? What were the errors? – Zoey Mertes Mar 22 '14 at 10:25
  • Using the PHP Variable `$_SERVER['REQUEST_URI']` you can get the path the user requested. Parse the URL using regex or another method and then use the found data to load the required files. This method requires that you rewrite all pages to the index file. This is how WordPress does it and a lot of other CMS's. – David Mar 22 '14 at 10:25

1 Answers1

2

You cannot rewrite a number to a name, unless you have some way of translating that number to a name. This means that on the http deamon level (Apache/.htaccess) you don't have enough information to redirect it. For redirects in php, see this.

Since you ask about rewrites in php, I'll answer that too. There is no such thing as rewriting in a php file. An internal rewrite maps one url (e.g. www.domain.com/category/cat-name) and lets the server execute a different url (e.g. www.domain.com/category.php?id=13). This happens on the http deamon level, in your case Apache.

First make a .htaccess in your www-root:

RewriteEngine on
RewriteRule ^category/[^/]+$ /category.php

In category.php:

if( strpos( $_SERVER['REQUEST_URI'], 'category.php' ) != FALSE ) {
  //Non-seo url, let's redirect them
  $name = getSeoNameForId( $_GET['id'] );
  if( $name ) {
    header( "Location: http://www.domain.com/category/$name" );
    exit();
  } else {
    //Invalid or non-existing id?
    die( "Bad request" );
  }
}

$uri = explode( '/', $_SERVER['REQUEST_URI'] );
if( count( $uri ) > 1 ) {
  $name = $uri[1];
} else {
  //Requested as http://www.domain.com/category ?
  die( "Bad request" );
}

This will redirect requests to category/name if you request category.php?id=number and get the name from the url if you request category/name

Community
  • 1
  • 1
Sumurai8
  • 20,333
  • 11
  • 66
  • 100