开发者

Htaccess - Silently converting pretty url to a php script with get var

I am using PHP and I want to use URLs like this:

http://www.example.com/username,

Instead of usin开发者_Go百科g a query string like this:

profile.php?u=username

How can I set up my .htaccess file to do this?


Something like this:

 RewriteCond %{REQUEST_FILENAME} !profile.php
 RewriteRule ^(.*)$ /profile.php?user=$1 [L]

This will pass anything after the domain name as a GET variable named user to http://www.example.com/profile.php

So this:

 http://www.example.com/User123

Will become:

 http://www.example.com/profile.php?user=User123

This will happen silently, so while your server will see the ugly profile.php URL, the browser will still show the "pretty" example.com/User123 version to the user.


Since you asked for a more thorough explanation on what's going on, here it is:

RewriteRule is a bit like an if statement. Basically you're saying "if the request matches this pattern, redirect the request to this other file."

The pattern we're matching against is ^(.*)$ which breaks down as follows:

  • ^ means "begin looking for a match at the very beginning of the string
  • .* means "match on any number (*) of any character (.)
  • $ means "stop matching at the end of the string.

When you combine these together, it basically amounts to "match any request."

The parentheses around .* tells mod_rewrite to store anything that matches the part of the rule they surround in a variable. The variable they get stored in is called $1 (if we had multiple sets of parentheses, they would be stored in $2, $3, and so on).

This $1 variable is used to define the new path specified in the last part of the RewriteRule.

RewriteCond is like throwing another if statement around the RewriteRule. It says "only execute the RewriteRule below if this condition is true."

In your case the RewriteCond says to only execute the rule if the file being requested in the URL (%{REQUEST_FILENAME}) isn't "profile.php"

The implication of this is that requests for "profile.php" are processed as normal, but requests for anything else are redirected to point to profile.php.

The [L] at the end just means "don't execute any RewriteRules after this one". The L stands for "Last".

Clear as mud?


RewriteEngine On
RewriteRule http://www.example.com/(.*) profile.php?u=$1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜