Jeremy
Jeremy

Reputation: 1161

Problem rewriting dynamic URLs using mod_rewrite

I'm trying to rewrite a dynamic URL using the following code:

RewriteRule (.*)/$ index.php?location=$1  
RewriteRule (.*)/(.*)/$ index.php?location=$1&company=$2

I really need two rewrites as you can see from the above code. First, I need the page to rewrite just the location if that's all there is. For example, it would turn site.ccom/index.php?location=sandiego into site.com/sandiego/
This is working correctly.

However, when I try to add in the second variable it fails. It manages to detect the &company=1 variable, but for some reason it returns the ?location=sandiego variable as 'index.php'. For example, if I input the following: site.com/san-diego/1/ and then try to grab the $location and $company variables, it will only get the $company variable successfully, and the $location variable will be set to 'index.php', rather than 'san-diego'.

Any help would be greatly appreciated.

Upvotes: 2

Views: 109

Answers (3)

Jeremy
Jeremy

Reputation: 1161

I think I found the solution. I'm using the following:

RewriteRule ^([a-z0-9-]+)/?$ index.php?location=$1 [NC]
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ index.php?location=$1&company=$2 [NC]

This seems to be working perfectly, and is successfully redirecting both site.com/sandiego/ and site.com/sandiego/1/

Upvotes: 1

Naraen
Naraen

Reputation: 3250

Try  ([^\/]*)/([^\/]*)/$  instead of (.*)/(.*)/$

Upvotes: 0

Maxime Pacary
Maxime Pacary

Reputation: 23011

Try those:

RewriteRule ^([a-z0-9]+)/?$    index.php?location=$1 [NC]
RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/?.*$    index.php?location=$1&company=$2 [NC]

Keep in mind that trying to capture any sequence of characters (by using for example (.*) or (.+)) when doing URL rewriting, is usually a bad idea, as explained in this thread : http://www.sitepoint.com/forums/apache-configuration-199/rewrite-eliminate-trailing-slash-arbitrary-parameters-520302.html#post3657601

Upvotes: 0

Related Questions