Reputation: 337
I need to rewrite URL from http://example.com/file.php?id=test&cat=category
to http://example.com/file?test&cat=category
I only achieved to rewrite path /file.php
to /file
with:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^/?(\w+)$ $1.php [QSA,NC,L]
How to rewrite the rest of URL? And second question: Is it possible to block default URL access so user must use rewrited URL?
Upvotes: 0
Views: 193
Reputation: 13169
To check on the values in a query string you need to use a RewriteCond with the QUERY_STRING
variable, like this:
RewriteCond %{QUERY_STRING} ^([a-z]+)&cat=([a-z]+)$
This says that the RewriteRule must only execute if the query string contains a set of consecutive lowercase letters followed by an ampersand, then "cat=" followed by another set of consecutive letters. The capture groups can be used in the next RewriteRule using %1
and %2
like this:
RewriteRule ^([a-z]+)$ $1.php?id=%1&cat=%2 [L]
You don't want to use the QSA
flag because that will append the user's invalid query string to the end of your rewritten URL. You may still want to use the NC
flag to ignore case in the match pattern, but it's probably best to work with lowercase-only filenames if possible.
Regarding blocking requests to the finalised (.php) path, I can't think of a way to do this, because even the finalised URL has to run through the .htaccess rules, so forbidding access to it would break the redirect.
Upvotes: 1