首页 > 解决方案 > 使用 htaccess 摆脱 /index.php 链接?

问题描述

我可以这样打开我的网站:

www.mysite.com

或像这样:

www.mysite.com/index.php

我想创建一个将 www.mysite.com/index.php 重定向www.mysite.com htaccess 规则。但我所有的尝试都有其他副作用。我试过了:

Redirect index.php    home.php
RewriteRule    ^index.php?$    home.php    [NC,L]
RewriteRule    ^index.php/?$    redirect_to_home.php    [NC,L]

但是所有这些都搞乱了原来的 index.php 调用。所以它会重定向,但正常的 mysite.com 链接不再起作用。

有任何想法吗?

标签: regexapache.htaccessmod-rewrite

解决方案


请您尝试以下操作。

RewriteEngine On
RewriteCond  %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} index\.php
RewriteCond %{REQUEST_URI} ^(.*/)index\.php$
RewriteRule ^ %1 [R=301,L]

解释:

  • 使RewriteEngine On规则起作用。
  • 提及条件,通过RewriteCond该条件REQUEST_FILENAME检查浏览器中是否存在提及的文件。
  • 然后检查THE_REQUEST其中是否包含请求的完整详细信息(包括 URL 和 GET/POST 方法),如果其中包含 index.php。
  • 现在检查是否REQUEST_URIindex\.php请求的 url 中,将之前的所有内容保存到临时缓冲内存中,以便稍后检索其值(基本上是其域名)。
  • 最后,RewriteRule使用 index.php 将完整的 URL 重定向到仅根据要求的域名(R=301 用于浏览器端的永久重定向)。

推荐阅读