Access Both URL With PHP and Non-PHP in PHP project after applying Htacces Rules
RewriteRule ^c/([a-zA-Z0-9-/]+)$ category.php?id=$1 [L]
RewriteRule ^p/([a-zA-Z0-9-/]+)$ detail.php?post=$1 [L]
Here I access both URLs like www.example.com/c/category-name
and www.example.com/category.php?id=12
but I want only www.example.com/c/category-name
URL. I don’t Want Duplicate URLs both this page.
2
Answers
With your shown samples, attempts please try following htaccess rules. Make sure to clear your browser cache before testing your URLs.
Unless you have changed an existing URL structure and
category.php
and/ordetail.php
have been indexed by search engines then you could simply force a 404 when either of these URLs are accessed directly.For example, the following should go before your existing rewrites:
The check against the
REDIRECT_STATUS
env var ensures that we are only checking direct requests and not rewritten requests by the later rewrite.Otherwise, if these "old" URLs have previously been indexed by search engines or linked to by third parties then you should redirect to the "new" (canonical) URLs instead. For example:
I’ve moved the hyphen to the end of the character class (ie. from
[a-zA-Z0-9-/]
to[a-zA-Z0-9/-]
) to avoid a potential ambiguity since hyphens are naturally special characters inside a character class.The
$1
backreference contains eitherc
orp
, depending on the request, to form the first path segment.%1
is the value captured from the URL-parameter. Importantly, this is the same regex you are using the later rewrite to match the value.NB: Test first with a 302 (temporary) redirect to avoid potential caching issues.