Php 使用.htaccess创建SEF URL

Php 使用.htaccess创建SEF URL,php,apache,.htaccess,Php,Apache,.htaccess,如何更改以下格式的url example.com/page/1 到 ? 我进去的时候 example.com/page/1 它应该重定向到 example.com/index.php?page=1 我需要在.htaccess文件中做哪些更改 文件夹结构如下所示 -Public_html .htaccess index.php 谢谢。在您的public\u html/.htaccess文件中使用此选项 RewriteEngine on R

如何更改以下格式的url

  example.com/page/1

?

我进去的时候

example.com/page/1
它应该重定向到

  example.com/index.php?page=1
我需要在.htaccess文件中做哪些更改

文件夹结构如下所示

   -Public_html
      .htaccess
       index.php

谢谢。

在您的
public\u html/.htaccess
文件中使用此选项

   RewriteEngine on
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^page/([0-9])/?$ /index.php?page=$1 [QSA,NC,L]

RewriteCond
检查请求的文件名或目录是否已存在,
RewriteRule
将被跳过。

您可以将此代码放入htaccess中

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^page/([0-9]+)$ index.php?page=$1 [NC,L]
只有使用此代码,您现在可以访问
http://example.com/page/55
并查看
/index.php?page=55的内容

但是。。。问题是,您仍然可以访问
http://example.com/index.php?page=55
并且它创建了一个重复的内容:非常不利于引用(谷歌和其他公司)

有关重复内容的详细信息:

解决方案:您可以添加另一条规则以重定向
http://example.com/index.php?page=55
http://example.com/page/55
没有任何无限循环

注意1:确保(在Apache配置文件中)已启用mod_rewrite并允许htaccess文件


注意2:由于您的规则创建了一个虚拟目录(
/page/
),如果您使用html资源的相对路径,您将遇到一些问题。请确保所有链接(js、css、图像、href等)都以斜杠开头(
/
),或者在
html标记之后添加一个基:

在我的回答中,我假设您使用的是linux, 我还假设你会遇到更复杂的情况,比如 您希望捕获的一个参数

example.com/page/1/3 在这种情况下,我认为您必须在index.php中解析url

首先,您必须在站点根目录中设置.htaccess文件,还必须确保在apache配置中启用mod_rewrite

在运行debian的情况下,您可以在终端中运行此命令 要确保启用此mod,请执行以下操作:

sudo a2enmod rewrite 
将htaccess文件添加到索引php文件所在的根目录中示例:

/var/www/html/.htaccess

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^.*$ ./index.php
</IfModule>
index.php请求example.com/page/1/2

$request = getUrlParams($rootPath);
$module = $request[0]; // page
$moduleValue = $request[1]; // 1
$moduleValue2 = $request[2]; // 2

考虑一个路由系统是好的。我会开发一个具有MVC模式的路由器类,使其更通用/可重用,而不是您的特定代码。但我真的怀疑,看看这个问题,OP需要一个像这个这样复杂的系统。顺便说一句,你的解决方案根本不能解决重复内容问题重复内容问题?不,这取决于你在index.php中做了什么如果你加载的是同一个页面,这是你的问题,但根据我的解决方案,你想对url值做些什么,比如加载不同的内容。是的,我错了,考虑到您没有捕获
page
get参数来提供内容
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^.*$ ./index.php
</IfModule>
/*
$base path is used only if you running your site under folder
example.com/mysitefolde/index.php
*/
function getUrlParams($basePath = ''){
  $request  = str_replace($basePath, "", $_SERVER['REQUEST_URI']);
  return  explode('/', $request);
}
$request = getUrlParams($rootPath);
$module = $request[0]; // page
$moduleValue = $request[1]; // 1
$moduleValue2 = $request[2]; // 2