user1759419
user1759419

Reputation: 15

How to rewrite url in php?

I have some question to ask about rewrite url in php.

1- www.test.com/index.php?name=123 to www.test.com/123

2- www.test.com/folder1/index.php?name=123 to www.test.com/folder1/123/index.php

Hereabout my coding on number 1 but i don't know how to rewrite number 2 combination with number 1:

RewriteEngine on
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteRule  ^(.*)$ index.php?usname=$1 [QSA,L]

Upvotes: 0

Views: 337

Answers (2)

Stephen M. Harris
Stephen M. Harris

Reputation: 7523

When you say "rewrite url in php", I assume that "in php" refers to the language of the application, not the rewrite/redirect method --- because your example code consists of Apache directives.

The rules below will change URLs in the form test.com/folder1/index.php?name=123 into a "pretty" URL of the form test.com/folder1/123 (I removed the 'index.php' to be even more user-friendly).

  1. Redirect the ugly query URL so users always see the "pretty" URL

    RewriteCond  %{QUERY_STRING} \bname=([^&]+)
    RewriteRule  ^/?folder1/index\.php$ /folder1/%1 [R=302]
    
  2. Tell the server how to interpret the pretty URL

    RewriteRule  ^/?folder1/([^\/]+)(/index\.php)?$ /folder1/index.php?name=$1 [L]
    

NOTE: The first rule above uses a 302 (temporary) redirect, so your browser doesn't "memorize" the redirect rule while you're testing and tweaking them. If you care about SEO, change the [R=302] to [R=301], which is a permanent redirect.

Upvotes: 1

Jonathan Muller
Jonathan Muller

Reputation: 7516

Try this one:

RewriteEngine on
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteRule  ^(.*)/([0-9]+)/index.php $1/index.php?name=$2 [QSA,L]
RewriteRule  ^(.*)$ index.php?usname=$1 [QSA,L]

The [L] instruction at the end of the rewrite rule means that if the rule match, it ends parsing the .htaccess.

So you have to place the rule before your rule ^(.*)$ wich handles every case

Upvotes: 0

Related Questions