Search code examples
php.htaccess

Apache htaccess rewrite url


Am trying to update my site URL structure but facing issue with htaccess rewrite rules.

my old url is like this : http://www.example.com/index-test.php?page=5

my goal is to rewrite it to something like this : http://www.example.com/page/5

so that when i visit http://www.example.com/page/5 it forward that to index-test.php.

so for that i have wrote these two rules but its not working

Options +FollowSymLinks
RewriteEngine on
RewriteBase /

RewriteRule ^page/?$  index-test.php [NC,L]
#RewriteRule ^page/([^/d]+)/?$ index-test.php?page=$1 [L,QSA]

so any idea whats wrong with my htaccess rules.


Solution

  • The regex you're looking for is :

    RewriteRule ^page/([0-9]+)$  /index-test.php?page=$1 [L]
    

    You need to catch the page id after "/" with a set of (). Then in the rewrite, you have to use $1 (linked to the catched id).

    Caution : This line will not work if you want access http://www.example.com/page/ without any id, if you want to, you can use :

    RewriteRule ^page/([0-9]+)*$  /index-test.php?page=$1 [L]