2

Been reading about this for a while now and I'm close but struggling with the final hurdle.

I have a url like this: site.com/detail/123/some-description/maybe-some-more-description

that I want to become

site.com/details.php?id=123

I've got this so far

RewriteRule detail/(.*)/.*$ details.php?id=$1

which according to this (https://htaccess.madewithlove.be/) results in

details.php?id=123/some-text

how do I get rid of the some-text on the end?

3 Answers 3

1

Try this:

  • The regex: (.*?detail)\/(\d+)\/.*
  • The replacement: $1.php?id=$2

Which results in site.com/detail.php?id=123.

They both can be tested at Regex101.

  • (.*?detail) matches the site base URL with details and captures to the group $1.
  • \/ matches the slash itself (must be escaped).
  • (\d+) matches the number and captures it to the group $2.
  • \/.* matches the rest of the URL and it helps to not include it in the replacement.

Edit: Do you mind the difference between detail and details?

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

3 Comments

Cool I think that does it. Don't think I need the first group, but this is essentially what I was looking for: detail\/(\d+)\/.*
So I've added this into Wordpress, which has generated the following in the .htaccess RewriteRule ^(.*)\/details\/([a-zA-Z0-9_]+)\/.* /detail/?id= [QSA,L] which doesn't seem to be working i can see it matches here regex101.com/r/5hniR0/3
It seems ok here: htaccess.madewithlove.be?share=7fe95f0b-48fc-5b3c-a296-3bfdbaa9… but doesn't seem to be working when I run it locally through Apache / Wordpress. Any ideas?
1

It seems that in your case you have one more group of /text/

Change your rule from: RewriteRule detail/(.*)/.*$ details.php?id=$1

to

RewriteRule detail/(.*)/(.*)/.*$ details.php?id=$1

If you don't know how many slashes there are you can just use group with excluded slash [^\/]*:

RewriteRule detail/([^\/]*)/.*$ details.php?id=$1

1 Comment

thanks for your very quick response. So do you need to know the number of following slashes ? I can't say for example store what is in the first slash as $1 and ignore everything following it ?
0

RewriteRule ^([A-Za-z0-9]+)$ file.php?key=$1 [L,QSA]

use in anchor tag

  <a href="details/<?php $id?>">

if you want receive value in variable $value = $_REQUEST['key'];

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.