Url rewriting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Url rewriting

Post by klevis miho »

How can i rewrite this url:
example.com/authors.php?name=Author-Name

into this:
example.com/Author-Name
?

Any help would be greatly accepted
phu
Forum Commoner
Posts: 61
Joined: Tue Mar 30, 2010 6:18 pm

Re: Url rewriting

Post by phu »

If you're deploying behind Apache (pretty common), you can use mod_rewrite via a .htaccess file in your site's root directory.

.htaccess example from Apache mod_rewrite Examples (search page for "Examples of mod_rewrite"):

[syntax]RewriteEngine on
RewriteRule ^([^/\.]+)/?$ /index.php?url=$1 [L][/syntax]
The regex may not be ideal for what you're trying to do, and the rewrite itself needs very minor tweaking (you should understand what it's doing before you deploy it anyway), but the article should be a good starting point.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Url rewriting

Post by John Cartwright »

In your .htaccess, you would have something like:
[text]
RewriteEngine On
RewriteRule ^([a-zA-Z-]+)$ authors.php?name=$1[/text]

However, you probably want some kind of flag to indicate it's an authors page, otherwise, you might intercept normal urls.

Perhaps something like

[text]RewriteEngine On
RewriteRule ^author/([a-zA-Z-]+)$ authors.php?name=$1[/text]
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Url rewriting

Post by klevis miho »

Oh yeah, thnx man. That's just what I needed.
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Url rewriting

Post by klevis miho »

Another thing.
I did this:
RewriteRule ^author/([a-zA-Z-]+)$ authors.php?name=$1

but now It doesn't get the css.

Anyone knows why?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Url rewriting

Post by John Cartwright »

Probably because your stylesheets are relative links. You need to change them to absolute paths since with your rewrite rule you are technically a directory level over the root directory.
Post Reply