Lior
Lior

Reputation: 5664

Best way to handle SEO URLs with PHP

I've got a PHP file called books.php, and I'd like to use SEO URLs using htaccess and PHP.

I would like to create rules for the following formats:
books.php?bookid=X (Optional: books.php?bookid=X&page=Y)
books.php?categoryid=X (Optional: books.php?categoryid=X&page=Y)
books.php?do=search&query=X
books.php?do=search&tag=X

These would be accessible through:
/books/book/{booktitle}
/books/category/{categorytitle}
/books/search/{search_string}
/books/tags/{tagtext}

What I'd like to know is the main idea for doing this.
Thanks!

Upvotes: 0

Views: 1701

Answers (3)

Chris Sobolewski
Chris Sobolewski

Reputation: 12925

I find it's easier to just do something like this:

/books/book/9834/{title}

Where the number is the database ID, and the plain-text title is just thrown away by the PHP. It's not as clean, but there's too many problems involving uniqueness if you try to pass the title in to a SQL query IMO.

Check out the mod-rewrite generator here for help building rules.

Upvotes: 5

HappyDeveloper
HappyDeveloper

Reputation: 12805

What about using a micro-framework or a full-blown framework?

This is the kind of problems they solve, so you can focus on building your application instead of building your tools.

Upvotes: 1

Eli
Eli

Reputation: 5610

The key piece here actually happens outside of PHP. You want to tell your webserver that instead of just looking for a file or directory with the given name, you actually want /books/foo/bar to call books.php with foo and bar as parameters. If you're using Apache, take a look at this: htaccess mod_rewrite

Once you get this set up, I would recommend redirecting all the old books.php URLs to their new "SEO URL" equivalent. Best practice is to have exactly one valid URL for each page.

Upvotes: 4

Related Questions