Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Rewrite Rules

The actually URL which my app uses is:

http://site.com/search.php?search=iPhone 

but I would like it to be possible to achieve the same with

http://site.com/iPhone

I have no experience of rewrite rules, how can I set this up?

The solution has worked but the new URL is displayed in the address bar. I thought it would have been possible to set this up so that it appears as though the page location is

http://site.com/iPhone

without changing to display

http://site.com/search.php?search=iPhone 

Is this possible? Thanks.

like image 727
MartinW Avatar asked Feb 17 '09 23:02

MartinW


People also ask

What is rewrite rules?

Definition of rewrite rule : a rule in a grammar which specifies the constituents of a single symbol.

What is $1 in Apache rewrite rule?

$1 represents the match from the first set of parentheses in the RewriteRule regex, not in the RewriteCond regex.

What is Apache rewrite rules?

RewriteRule specifies the directive. pattern is a regular expression that matches the desired string from the URL, which is what the viewer types in the browser. substitution is the path to the actual URL, i.e. the path of the file Apache servers. flags are optional parameters that can modify how the rule works.


2 Answers

Create a file called .htaccess in the root of your website and put this in it.

RewriteEngine on 
Options +FollowSymlinks
RewriteBase / 

RewriteRule ^(.*) search.php?search=$1 [R]

Should do the trick.

I would suggest however that you make it a bit more specific, so maybe require the user of a search directory in your url. eg instead of mysite.com/IPhone use mysite.com/search/IPhone which would work like

RewriteEngine on 
Options +FollowSymlinks
RewriteBase / 

RewriteRule ^search/(.*) search.php?search=$1 [R]

This makes it easier to have normal pages that arnt redirected, such as about us or a basic homepage.

As Chris says, this is not PHP but Apache that does this, and whether it works can depend on your hosting setup.

like image 105
Toby Allen Avatar answered Nov 09 '22 22:11

Toby Allen


You need to specify something like this in your .htaccess file:

RewriteEngine on
RewriteRule /(.*) /search.php?search=$1

Check also:

  • mod_rewrite: A Beginner's Guide to URL Rewriting
  • Module mod_rewrite, URL Rewriting Engine
like image 42
Christian C. Salvadó Avatar answered Nov 09 '22 21:11

Christian C. Salvadó