dusan
dusan

Reputation: 19

How to rewrite HTTP get request with .htaccess?

I want to rewrite HTTP get request. It request looks like this

example/index.php?opt=1&cat=1

I used this rule on my .htaccess

Options +FollowSymLinks
RewriteEngine on
RewriteRule /(.*)/(.*) index.php?opt=$1&cat=$2

and it works fine.

So when I type example/index/1/1 it goes on page example/index.php?opt=1&cat=1,
when I type example/index/1/2 it goes on page example/index.php?opt=1&cat=2.

But when I click on example/index/1/3 it does not go on example/index.php?opt=1&cat=3. How can I rewrite rule. Is it possible to rewrite multiple HTTP get request on same project, because I have and something like this example/demo.php?par1=x&par2=y

Upvotes: 1

Views: 368

Answers (1)

arkascha
arkascha

Reputation: 42885

As mentioned in the comment above, the issue with the third example url pointing to the index script is probably a caching issue. Try making a deep reload or clear your browser cache.

For a more general rewriting rule handling similar patterns:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/example/([^/]+)/
RewriteRule /(.*)/(.*) %1.php?opt=$1&cat=$2

Note however that the regular expression you use inside that RewriteRule is not robust: depending on the structure of your incoming requests you might experience unexpected behavior. I would suggest something like this instead, which assumes that you place that .htaccess style file in your DocumentRoot:

RewriteEngine on
RewriteRule ^example/([^/]+)/([^/]+)/([^/]+)/? $1.php?opt=$2&cat=$3 [QSA]

And last not least some general note: if you have control over the http servers configuration you should always prefer to place such rules inside the host configuration instead of using .htaccess style files. Those files are notorioously error prine, make things complex, are hard to debug and really slow the server down. They only make sense if you do not have control over the server configuration or if an application needs to make dynamic changes to the setup.

Upvotes: 1

Related Questions