How to do URL re-writing in PHP?

2018-12-31 18:22发布

I am trying to implement URL rewriting in my PHP application. Can someone share a step by step procedure of implementing URL rewriting in PHP and MySQL?

In my application I want to implement following URL rewriting, I want to redirect

1. http://example.com/videos/play/google-io-2009-wave-intro
2. http://example.com/videos/play/203/google-io-2009-wave-intro

to

1. http://example.com/videos/play.php?title=google-io-2009-wave-intro
2. http://example.com/videos/play.php?id=203

Please tell me how to implement both URL rewriting in any of the above way.

One more thing which URL will be best according to SEO, management, application point-of-view out of the following two types.

1. http://example.com/videos/play/google-io-2009-wave-intro
2. http://example.com/videos/play/203/google-io-2009-wave-intro

9条回答
浮光初槿花落
2楼-- · 2018-12-31 18:46

Using mod rewrite:

RewriteRule ^videos/play/([0-9]+)/([^.]+)$ play.php?id=$1&name=$2

example.com/play.php?id=203&name=google-io-2009-wave-intro

would work as

example.com/videos/play/203/google-io-2009-wave-intro

查看更多
美炸的是我
3楼-- · 2018-12-31 18:49

If your server supports it (apache / mod_rewrite), you can use a .htaccess file to re-direct the visitor.

Something like (just a draft, adapt to your own needs...):

RewriteEngine On
RewriteRule ^([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)/([-0-9a-zA-Z]+)/?$ /$1/$2.php?id=$3 [L]

for the second example.

查看更多
泪湿衣
4楼-- · 2018-12-31 18:52

Sorry about not giving you detailed explanation, but maybe you could take a look at DokuWiki for a starting point.

In its setup it accepts 3 modes:

  1. Regular urls: ?id=zzz
  2. .htaccess rewrite: uses apache to do the rewritting
  3. internal (php) rewrite: urls end up looking like http://www.example.com/kb/doku.php/start

It's free so you can just download and browse the code.

As a note, the apache redirect is very likely the best solution but the pure php one is also interesting in case your code is going to run in IIS6 servers where rewritting is not as easy as in apache.

查看更多
登录 后发表回答