PHP Rewrite Rules

前端 未结 3 906
心在旅途
心在旅途 2020-11-30 06:56

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 wit

相关标签:
3条回答
  • 2020-11-30 07:39

    Rewrite rules aren't part of PHP as far as I'm aware, but Apache (specifically mod_rewrite) or whatever server you're using. For Apache, you need on the server to have a file called .htaccess, and in it put something like:

    RewriteEngine on
    RewriteRule ^(\w+)/?$ /index.php?search=$1
    

    ^(\w+)/?$ is a regular expression - it matches any word of 1 or more characters, followed by a / maybe. So it changes site.com/iPhone into site.com/index.php?search=iPhone. Sound about right?

    0 讨论(0)
  • 2020-11-30 07:43

    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
    0 讨论(0)
  • 2020-11-30 07:49

    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.

    0 讨论(0)
提交回复
热议问题