如何通过.htaccess重命名第一个参数

时间:2012-03-09 12:25:09

标签: php .htaccess

如何在.htaccess文件的帮助下将我的第一个参数重命名为任何变量?

例如,对于http://localhost/mysite/index.php,我想将index.php或任何其他页面名称重命名为某个特定名称。

即。 .htaccess返回以下网址

http://localhost/mysite/page

“page”可以是任何页面名称,即index.php,about.php等等。

4 个答案:

答案 0 :(得分:1)

仅限“允许”带有字母的页面:

RewriteEngine on
RewriteRule ^mysite/([a-z]+)$ http://localhost/mysite/$1.php [L]

要“允许”包含任何字符的网页

RewriteEngine on
RewriteRule ^mysite/([.]+)$ http://localhost/mysite/$1.php [L]

答案 1 :(得分:0)

使用Mod_rewrite重写您的网址。这是基于模式的。

首先将此添加到.htaccess

选项+ FollowSymlinks

上的RewriteEngine

这会打开重写引擎。然后定义一个必须捕获的模式&重写:

RewriteRule ^ page /([^/.]+)/?$ ^ .php [L]

我认为这条规则会做你要求的重写。有关更多信息,请在google上查看mod_Rewrite用法的示例

答案 2 :(得分:0)

您通常会将一个slug或请求URI作为查询字符串的一部分,然后使用.htaccess和PHP的组合来重写该传入请求。

例如,您可以在.htaccess文件中解决此问题,以捕获所有传入的请求:

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

这将重写任何尚未成为文件或目录的传入URL。因此 http://example.com/page 会匹配。

然后在index.php脚本中,您将获得类似于以下内容的内容:

<?php
$parts = explode('/', $_GET['url']);

这只是将您的网址拆分为斜杠,因此如果请求的网址为 / page / about-us ,您将获得一个如下所示的数组:

array(2) {
  [0]=> string(4) "page"
  [1]=> string(8) "about-us"
}

希望这有帮助。

答案 3 :(得分:-1)

不需要htaccess,请使用:

RedirectMatch /mysite/index.php http://localhost/mysite/page