2

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.

3 Answers 3

1

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/

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

Comments

0

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

3 Comments

Sorry, neither of those work at all. They both returned with 404 errors.
Sorry, I've renamed index.php to rewrite.php for testing and forgot to change that back... => edited my answer.
Yeah, a figured that, and renamed to index.php. It still doesn't work however. Going back to my original code, I can get either one or the other to work. If I just use this line: RewriteRule (.*)/$ index.php?location=$1 it redirects site.com/sandiego/ perfectly. And if I use just this line: RewriteRule (.*)/(.*)/$ index.php?location=$1&company=$2 it redirects to site.com/sandiego/1/ perfectly. However, when I use them together it all breaks down.
0
Try  ([^\/]*)/([^\/]*)/$  instead of (.*)/(.*)/$

1 Comment

Thanks for your response, but I think I've solved the problem (posted below). I will get back to you if my solution doesn't work, and will test your approach. Thanks again.

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.