3

I've been working on this for a couple of days now and I'm wondering if anyone could point me in the right direction please... I'm trying to pass two variables in my rewrite.

Unless the given url is a file or directory, I'd like all urls to be dynamically rewritten as follows:

example.com/category -> example.com/index.php?p=category
example.com/category/page -> example.com/index.php?p=category&article=page
example.com/category2/page -> example.com/index.php?p=category2&article=page

I'm having a hard time trying to turn the following in something dynamic:
RewriteRule ^category/(.+?)$ ?p=category&article=$1 [L]

I'm trying this but it doesnt work:
RewriteRule ^(.+?)/(.+?)$ ?p=$1&article=$2 [L]

...also trying this but it doesnt work either:
RewriteRule ^(.*)/(.+?)$ ?p=$1&article=$2 [L]

I'm trying to avoid putting in the following to make it work:
RewriteRule ^category2/(.+?)$ ?p=category2&article=$1 [L]

Here is the full code:

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^category/(.+?)$ ?p=category&article=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ?p=$1 [L]

UPDATE:

This actually did it for me:

RewriteRule ^([^/]+)(/([^/]+))? ?p=$1&article=$2 [L]

Thank you!! Andrew

4
  • I forgot that the second parameter is optional, congratulation, but are you sure $2 is outputting the second parameter "page" in the OP correctly? I think it'll output "/page" instead Commented Feb 8, 2016 at 0:44
  • check the updated answer Commented Feb 8, 2016 at 1:02
  • your correct, it should be $3. thank you for that! Commented Feb 8, 2016 at 1:57
  • You're welcome and I'm glad it helped, enjoy coding. Commented Feb 8, 2016 at 2:14

1 Answer 1

2

I'm not an expert but I think this will do it for you:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]+)/([^/]+) index.php?p=$1&article=$2         [L]

Where [^/]+ matches everything except /, result when tested on htaccess.madewithlove.be

enter image description here


EDIT:

as I totally forgot that the second parameter is optional, the great update in the OP almost did it except the fact that it adds a / at the start of parameter2 value, because $2 is capturing the outer group, while we need the inner one, as shown in this image:

enter image description here


Instead replace $2 with $3 and this should fix it:

RewriteRule ^([^/]+)(/([^/]+))? ?p=$1&article=$3   [L]

enter image description here

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

Comments

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.