开发者

How do I remove a variable name from a URL using htaccess?

So basically I want users to be able to go to my website with a URL of something like /45678, instead of having to use /?p=45678, so really I just want to remove the variable name. I've tried using mod_rewrite, but it seems that is only for removing the name when the page is visited.

Here is the current code:

RewriteEngine On 

RewriteCond %{QUERY_STRING} ^p=([0-9]+=$
开发者_StackOverflow
RewriteRule ^/$ /%1 [R]


Simply change all of your links to /45678 rather than ?p=45678. Or did I misunderstand you completely? Because what I got from your post is that it works properly, unless you manually access the ?p=45678 where as it stays as ?p=45678.

EDIT:
This is what I am using for http://www.madphp.org/dev/, give it a go, works like a charm for me (it also removes the index.php part). To access your now cleaner URL you would simply explode the $_SERVER['PATH_INFO'] variable to get all of the required parameters within your PHP script.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]


Have you set up mod_rewrite correctly? If so, you can use variables like simple $_GET variables, in this case you must access $_GET['p'] in PHP.


I did this without using .htaccess, but it does query a database. I wrote this a while ago so it uses PEAR DB, adjust to your database/connection method. I'll just copy my code and let you figure out what changes you need.

$db=connect_db();
$name=substr($_SERVER['PHP_SELF'], 20);
$name=strtolower($name);
$id=$db->getone("select id from user where login='{$name}'");
header("Location: /dragonart/profile?user=" . $id);

If you store your information in a database this may be a nice alternative. The downside is that the the URL is not rewritten and the user is ultimately sent to a page with ending in a $_GET variable.

edit:
Just realized that using my method a simpler method can be used for the answer. Since my solution was used to find the id of a user using their username and then send someone to their profile (which requires the id) a better solution would be something like:

$var=substr($_SERVER['PHP_SELF'], $length);  
header("Location: /path/to/page?p=".$var);

where $length is the usual length of the URL without the variable at the end.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜