Abishek
Abishek

Reputation: 11711

Rewrite URL in PHP

I would like to rewrite the following URL

www.mysite.com/mypage.php?userid=ca49b6ff-9e90-446e-8a92-38804f3405e7&roleid=037a0e55-d10e-4302-951e-a7864f5e563e

to

www.mysite.com/mypage/userid/ca49b6ff-9e90-446e-8a92-38804f3405e7/roleid/037a0e55-d10e-4302-951e-a7864f5e563e

The problem here is that the php file can be anything. Do i have to specify rules for each page on the .htaccess file?

how can i do this using the rewrite engine in php?

Upvotes: 2

Views: 188

Answers (4)

Willem Mulder
Willem Mulder

Reputation: 14014

If you want to rewrite the latter URL that is entered in the browser TO the first format, you would want to use a .htaccess file.

However, if you want to produce the pretty URLs in PHP (e.g. for use in link tags), then you have two options.

  • First, you could simply build the URL directly (instead of converting) which in my opinion is preferred.
  • Second, you could rewrite the first (ugly) URL to the pretty latter URL. You would then need to use preg_replace() in PHP. See http://php.net/manual/en/function.preg-replace.php for more info. Basically, you would want to use something like

    $rewrittenurl = preg_replace("@mysite\.com\/mypage.php?userid=(([a-z0-9\-]).+)\&roleid=(([a-z0-9\-]).+)$", "mysite.com/userid/$1/roleid/$2", $firsturl);
    

Good luck!

Upvotes: 0

Ben Lee
Ben Lee

Reputation: 53349

To get the rewrite rule to work, you have to add this to your apache configs (in the virtualhost block):

RewriteEngine On
RewriteRule ^([^/]*)/userid/([^/]*)/roleid/(.*)$ /$1.php?userid=$2&roleid=$3 [L,NS]

RewriteRule basically accepts two arguments. The first one is a regex describing what it should match. Here it is looking for the user requesting a url like /<mypage>/<pid>/roleid/<rid>. The second argument is where it should actually go on your server to do the request (in this case, it is your php file that is doing the request). It refers back to the groups in the regex using $1, $2, and $3.

Upvotes: 2

Bazzz
Bazzz

Reputation: 26942

No you don't need a separate rule for every php file, you can make the filename variable in your regex something like this:

RewriteRule ^(a-z0-9)/userid/([a-z0-9].+)/roleid/([a-z0-9].+)$ $1.php?userid=$2&roleid=$3

Upvotes: 0

Dezigo
Dezigo

Reputation: 3256

    RewriteEngine on
    RewriteBase /
    RewriteRule ^mypage\/userid\/(([a-z0-9]).+)\/roleid\/(([a-z0-9]).+)$ www.mysite.com/mypage.php?userid=$1&roleid=$2

Upvotes: 0

Related Questions