Andrik007
Andrik007

Reputation: 57

How can I split URL with htaccess by "?"

For example:

ex.com/read?id=1

should open

ex.com/route.php?action=read&id=1

but url won`t changing.

Upvotes: 0

Views: 558

Answers (2)

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

Try this :

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)\?id=(.+)\sHTTP.*$
RewriteRule ^(.*)$         /route.php?action=$1&id=%2 [QSD,R=301,L,NE]
RewriteCond %{QUERY_STRING} ^action=(.*)&id=(.*)$
RewriteRule  ^    /%1?id=%2 [QSD,L,NE]

First I match request that contains query string id=whatever then redirect it with new query string. Then I match new URI which contains new query string action=whatever&id=whatever and redirect it internally to same original path.

QSD flag is is available in Apache version 2.4.0 and later https://httpd.apache.org/docs/trunk/rewrite/flags.html , I added to discard previous query string and prevent it to be appended.

Clear browser cache then test these rules .

UPDATE: As per your comment , you want to open /route.php?action=read&id=1 internally while /read?id=1 in browser so , you could do what starkeen answered , but with specific query string and general URI it should look like this :

RewriteEngine on
RewriteCond %{QUERY_STRING} ^id=(.*)$
RewriteRule ^(.*)$  /route.php?action=$1 [QSA,L]

So if query string is existing and strat with id=whatever , /abc?id=123 will get internally from /route.php?action=abc&id=123 and the previous query string will be appending with new one

Upvotes: 2

Amit Verma
Amit Verma

Reputation: 41249

You can use the following RewriteRule in your /.htaccess :

RewriteEngine on

RewriteRule ^read/?$ /route.php?action=root [QSA,L]

This will rewrite /read?id=1 to /route.php?action=read&id=1 . You do not read to write &id=1 in the Rule's destination as QSA automatically adds it to the Rewrite destination.

Upvotes: 0

Related Questions