0

So I want to use mod_rewrite to transform:

random_name.com/main.php?user=$user

into

random_name.com/$user

(the $user is a php variable added onto the url, so it can be any name such as andy or rebecca, names like that)

and my code for the .htaccess is:

RewriteEngine on
RewriteRule ^/([A-Za-z0-9-]+)/?$ main.php?id=$1 [NC,L] 

But this doesn't seem to work for some reason. I've read up on the tutorials but they're really complicated and it seems like this would do the trick, but it doesn't. I'll appreciate it if anyone who has experience with mod_rewrite would give me a few pointers.

3
  • 2
    try it without the leading /. it's basically implied in a url, so isn't included in the URI being matched. Commented Mar 23, 2012 at 3:08
  • @MarcB You should post that as an answer. It helps to read the docs, see the last example and how the per-directory configuration (.htaccess) differs to the per-server one above it. Commented Mar 23, 2012 at 3:11
  • Hey I tried this, it didn't seem to work o.o. Commented Mar 23, 2012 at 3:12

2 Answers 2

3

You cannot use mod rewrite to transform random_name.com/main.php?user=$user into random_name.com/$user.
You have to do it manually in all the links on your site.

After that you may use mod rewrite for the reverse transformation, which will make /main.php?user=$user out of /user request

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

RewriteEngine on
RewriteRule ^([A-Za-z0-9-]+)$ main.php?user=$1 [NC,L] 

5 Comments

What about RewriteRule (.*) main.php?user=$1 [NC,L]? It's not the same, but if it works, you can then improve the regexp or work on the $_GET['user'] variable in your PHP code.
Hey Andres, just a quick question. I used a $_POST['user'] instead of a $_GET['user'] and then added some php code like $user=$_POST['user']; and header( "Location: main.php?user=$user" );. Am i suppose to use a $_GET instead of a $_POST?
And the above code that you posted, that transferred me to random_url.com/login.php. login.php is the login verification script, so it didn't transfer to main.php :O
The rewrite rule sends you to main.php, but there might be something on the PHP side redirecting you to login.php.
Answering your previous comment, yes, you should use either $_GET['user'] or $_REQUEST['user'], because when you use "main.php?user=$user", you are sending the information as a GET parameter. $_POST is to be used when you're posting that information to a page (for example using an HTML form or a POST request via AJAX or whatever).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.