1

I've got this url
category/product/index.php?itemid=WdS7Dk3L&title=new-product

I'd like to rewrite it to this and where second parameter is optional
category/product/WdS7Dk3L/new-product
or
category/product/WdS7Dk3L/

My htaccess is placed in
category/product/.htaccess

I've got this from this post, but I can't get it to work.
RewriteRule ^category/product/([^/]*)/?(.*)$ index.php?itemid=$1&title=$2

Please help me point to the right direction. Thanks.

Community
  • 1
  • 1
scorpion
  • 75
  • 9

1 Answers1

1

.htaccess file rewrite matches are relative to the location of the .htaccess file, so use this:

RewriteRule ^([^/]+)(?:/(.*))?$ index.php?itemid=$1&title=$2

You only specified the second parameter as optional, so I changed the first * (zero or more) to a + (one or more, as in something there) and removed the ? (optional) on the slash since it was in both your examples.

Update

The match was updated to make the slash after the first parameter optional when no second parameter is provided.

  • 1
    Great. I notice you're new to SO. The thing to do with a correct answer is accept it with the tick at the top left, and now you have more than 15 reputation you can upvote it too to say it was useful (the up arrow near the tick). This gives me some reputation for the answer and helps others easily see that it worked for you. Thanks! –  Jan 12 '17 at 20:51
  • Can I ask one more question about this? What do I have to do to accept trailing slash and not? `category/product/WdS7Dk3L/` and `category/product/WdS7Dk3L` – scorpion Jan 13 '17 at 20:29
  • Nope...I'm sorry but URL with trailing slash works `category/product/WdS7Dk3L/` but without trailing slash it doesn't `category/product/WdS7Dk3L` when only the first parameter is provided. – scorpion Jan 13 '17 at 21:00
  • It works this way with 2 rules.`RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?itemid=$1 [L]` `RewriteRule ^([^/]+)/(.*)$ index.php?itemid=$1&title=$2` – scorpion Jan 13 '17 at 21:35
  • Ah, sorry, I misunderstood and previously had added an optional trailing slash to the second parameter, not the first. That's done now. –  Jan 13 '17 at 21:40