mrpatg
mrpatg

Reputation: 10117

How do .htaccess redirects work?

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

Upvotes: 0

Views: 561

Answers (2)

Gumbo
Gumbo

Reputation: 655219

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)

Upvotes: 0

Greg
Greg

Reputation: 321588

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

Upvotes: 3

Related Questions