views:

160

answers:

2

I am trying to understand how .htaccess redirects work.

Say for instance, my user navigates to:

www.website.com/users/bob

How can I redirect that user to:

www.website.com/users.php?user=bob

+3  A: 

Your .htaccess would look something like this:

# turn on the engine
RewriteEngine On

RewriteRule ^users/(.*)$ /users.php?user=$1

# Pattern:
# ^      = start of URL (.htaccess doesn't get the leading "/")
# users/ = your path
# (.*)   = capture any character, any number of times
# $      = end of string

# Result:
# /users.php?user= = your path
# $1               = the first group captured in the pattern
Greg
You should probably also mention RewriteBase above.
Lior Cohen
now the $1...if i wanted to add a second rule here, but instead of website.com/users/bob, it would be website.com/show/whatever, and redirect that to website.com/show.php?id=whatever. Would i simple copy that line, change the specifics, and put a $2 at the end?
Patrick
No you'd still use $1 - it's the group in the associated rule. For example you could have /users/bob/bobbinson, match /users/([^/]*)/(.*)$ then $1 is bob and $2 is bobbinson
Greg
A: 

I recommend you to read the technical details of mod_rewrite. There you get a good insight into the internal processing.

For your specific example, a suitable rule might look like this:

RewriteRule ^users/([a-z]+)$ users.php?user=$1

Now when /users/bob is requested, mod_rewrite will:

  1. strip the contextual per-directory prefix (/ if the .htaccess file is located in the document root) from the requested path
  2. test the rest (users/bob) against the patterns until one matches
    • if there are any corresponding RewriteCond directives they, would be tested too
  3. replace the current URL with the new one (while replacing the $n and %n with the corresponding matches), if the pattern matches and the conditions are evaluated to true
  4. add the contextual per-directory prefix back, if the replaced URL is not already an absolute URL path (beginning with /) or absolute URL (beginning with the URL scheme)
Gumbo