Guru G Gulab
Guru G Gulab

Reputation: 23

Unable to solve .htaccess url rewriterule, gives 404 for all pages

I want to show URL like below examples:

1) http://www.domainname.com/detail/name/123.html

2) http://www.domainname.com/detail/124.html

In both URLs I want to show if "name" exist then want to display URL with "name" otherwise without "name".

1) RewriteRule ^detail/(.*).html$ detail.php?id=$1 [QSA]
2) RewriteRule ^detail/(.*)/(.*).html$ detail.php?id=$2 [QSA]

First rule is working file without "name". Second rule is not working and gives 404 for all pages.

Thanks in Advance.

Upvotes: 1

Views: 56

Answers (2)

Sumurai8
Sumurai8

Reputation: 20745

The problem you are having, is that the first rule matches both your first and second case. Obviously when id is name/123 your application can't handle it. What you want to do is limiting the characters to non-slash characters. After all, that means it can only match the last path segment. Besides that, force yourself to always escape literal dots in a regex. A dot matches pretty much anything if you don't do that...

RewriteRule ^detail/([^/]+)\.html$ detail.php?id=$1 [QSA,L]
RewriteRule ^detail/[^/]+/([^/]+)\.html$ detail.php?id=$1 [QSA,L]

Upvotes: 0

anubhava
anubhava

Reputation: 785971

You can use just one rule to handle both cases:

RewriteRule ^detail/(?:[^/]+/)?([^./]+)\.html$ detail.php?id=$1 [L,NC,QSA]

Upvotes: 1

Related Questions