Architheutus
Architheutus

Reputation: 73

Rewriting url having more than one url parameter

Has been researching on how to rewrite url using htaccess file. After much time invested, I still have very vague idea of how a url will be rewritten.

Basically, I have a url:

http://mehthesheep.com/bali/jimbaran/blue-point/1

I would like to rewrite to:

http://mehthesheep.com/countries/hotel.php?hotel_id=1&state=bali&city=jimbaran

How do I go about having more than one parameter in the url?

Any help with some simple explanation would be appreciated!

Upvotes: 1

Views: 64

Answers (2)

anubhava
anubhava

Reputation: 785146

Put this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ /countries/hotel.php?hotel_id=$4&state=$1&city=$2 [L,QSA]

Upvotes: 0

Brodie
Brodie

Reputation: 8717

So apache isn't my strongest skill, but from what I understand the way you would rewrite the urls is with mod rewrite, and in your regex, each matching parameter can be mapped to something else. So something like:

                 #1st field                                           #match 2 
RewriteRule ^/hotel/(.*)/(.*)  http://www.example.com/hotel.php?hotel_id=$2&state=$1 [NC,QSA,L]
                      #2nd field                                               #match 1

My syntax might be wrong so I apologize, but the gist is that I can take patterns and then correspond the matches to '$n' keys in my rewrite url. In the above example a call to /hotel/bali/1 would rewrite to hotel.php?hotel_id=1&state=bali. Not sure if it matters, but I used a very simple match '(.*)' basically means anything.

The last bit w/ are flags you can add to make sure you get the desired behavior. QSA allows for a querystring to be attached in case you had tracking or other params come in, NC makes the matching case insensitive, in the event they try something like /Hotel. L is for last, meaning if the rule is matched this is the last rule to evaluate so execute the rewrite (or something to that effect).

Hope that helps. This really helped me dig into mod rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html

Upvotes: 2

Related Questions