简单的mod_rewrite - 所以我再也不用考虑了

时间:2009-12-22 01:45:41

标签: php .htaccess mod-rewrite

不确定你将如何处理这个问题,但是......

每当我尝试让我的网址看起来漂亮时,我总是乱搞太长时间,这根本不值得麻烦。但如果这是一项简单的任务,那么最终效果就会很好。

所以我想要做的是创建一个方法,最终会产生类似......

的东西
index.php?do=user&username=MyUsername //This becomes...
/user/MyUsername //...that
index.php?do=page&pagename=customPage //And this becomes...
/page/customPage //...that
index.php?do=lots&where=happens&this=here //This also becomes...
/lots/happens/here //...that
index.php?do=this&and=that&that=this&and=some&more=too //And yes...
/this/that/this/some/more //This becomes this

那么我就做一个很好的.htacess文件,我再也不用看了。世界上的一切都会好一些,因为我们拥有漂亮的网址,而且我的头脑并没有受到影响。

3 个答案:

答案 0 :(得分:2)

您可以使用不同的方法将url放入单个参数中,并在应用程序中解析它。

所以apache重写规则看起来像:

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

将按以下方式转换您的网址:

/user/MyUsername => index.php?q=/user/MyUsername
/page/customPage => index.php?q=/page/customPage
...

在你的应用程序中,你有一个$ _GET ['q']变量,可以用'/'拆分,并按顺序排列你的参数。在PHP中,它将类似于:

$args = explode('/', $_GET['q']);
$ args将是一个包含'user','MyUserName'等的数组

这样您就不必再次触摸.htaccess,只需触摸您的应用逻辑。

答案 1 :(得分:1)

/user/MyUsername ==> index.php?do=user&username=MyUsername/page/customPage ==> index.php?do=page&pagename=customPage,您可以使用:

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)$ index.php?do=$1&$1name=$2 [L]

但我不认为你可以为/lots/happens/here/this/that/this/some/more写一个包罗万象的规则,因为你需要告诉mod_rewrite如何翻译这两个网址。

请记住,mod_rewrite必须将/lots/happens/here翻译成index.php?do=lots&where=happens&this=here,而不是相反。

答案 2 :(得分:0)

最好的方法是委托你的应用程序生成“漂亮的URL”,并解析和解释它们,并使用mod_rewrite只用这样的规则重写对你的应用程序的请求:

RewriteRule %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

此规则会将无法直接映射到现有文件的所有请求重写为 index.php 。然后,$_SERVER['REQUEST_URI']可以获得最初请求的URL(更准确地说:URL路径加查询)。

相关问题