在PHP中更改URL格式

时间:2015-06-26 09:00:23

标签: php apache .htaccess mod-rewrite url-rewriting

我想更改此格式

 http://mysite.tld/go.php?id=20 

 http://mysite.tld/20

如何使用PHP实现这一目标?

3 个答案:

答案 0 :(得分:4)

在Root / .htaccess文件中尝试此操作:

RewriteEngine On
RewriteCond %{THE_REQUEST} /go\.php\?id=([^\s]+) [NC] 
RewriteRule ^ /%1? [NC,R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ go.php?id=$1 [QSA,L,NC]

答案 1 :(得分:3)

As mentioned in previous answers, the usual way is to use Apache's Rewrite Engine via the .htaccess file.

If you're looking for a PHP specific solution:

  1. Redirect all incoming requests to a single PHP page.
  2. On this page, firstly retrieve the URL entered using the pre-defined $_SERVER array, excluding the base URL. ($_SERVER["HTTPS"],$_SERVER['HTTP_HOST'],$_SERVER['REQUEST_URI'])
  3. Once you have this, split up the URL into key and value pairs using the appropriate Regex. ('@/@')
  4. Map the keys to keys of an array that stores page references.
  5. Redirect to this page with POST or GET parameters of the values.

答案 2 :(得分:0)

您希望服务器处理此问题,而不是PHP。

如果您的服务器支持.htaccess文件,您可以创建它并添加:

RewriteEngine On
RewriteRule ^([^/]*)$ /go.php?id=$1 [L]

这将允许您访问

example.com/20但被调用的页面将为go.php?id=20