清除核心PHP中的url


clean url in core PHP

我已经浏览了clean url的多个线程,但我仍然对此感到困惑。我想在核心php网站中使用clean url策略。我为多个url更改了.htaccess文件。但是下面的代码只适用于一个页面(一个url)

 # Turn on the Rewrite Engine
 RewriteEngine on
 # Rewrite for buyleads.php
 RewriteRule ^buyleads buyleads.php [NC,L]
 ## NC makes the rule non case sensitive
 #L makes the last rule that this specific condition match
 # Rewrite for search.php?u=xxx
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$  search.php?cat=$1 [L]

 # Rewrite for search.php?u=xxx&subcat=xxx
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^([^/]+)/([^/]+)$  search.php?cat=$1&subcat=$2 [L]
 # Rewrite for detail.php?u=xxx
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^detail/([a-z0-9]+)$ /detail.php?id=$1 [L]

问题1。上面的代码只适用于search.php,如果我输入www.sitename.com/detail/29(detail.php代码),它的工作原理就像www.sitename/29(search.php)。我在中犯了什么错误

问题2。我还想知道是否真的可以通过.htaccess文件制作所有这样的url?有什么方法可以在核心php中创建吗?

问题3。最后,我想知道如何通过.htaccess自动重定向到干净的url,比如点击后点击这个用户应该去www.sitename.com/34/50。

提前感谢

关于您的问题:

  1. 您的第二个重写规则不排除以detail/开头的URL,因此永远不会到达您的第三个规则,因为第二个规则将搜索类别detail和子类别29(在您的特定示例中)。您可以将detail/从第二条规则中排除,但也可以更改第二条和第二条的顺序以使其工作
  2. 是的,您可以重写所有url,并将逻辑全部放在php中。您可以发送原始路径作为参数,并在php中解析/分析它
  3. 您应该首先正确生成链接。这样,你就不必重定向,也不必在重定向时告诉搜索引擎页面已被永久移动

第2点的一个小例子:

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

现在,所有的url都将被重写,在您的脚本中,您可以在$_GET['url'] 中获得原始的url/路径

这对于所有在Apache配置(httpd.conf或apache2.conf)中使用语言/内容协商以及重写规则的页面都是可能的。不需要使用.htaccess文件。

在apache2.conf文件(或httpd.conf)中添加Multiviews指令、MultiviewsMatch指令,以及这些重写规则

<Directory /var/www/html>
    Options Indexes FollowSymLinks Multiviews
    AllowOverride None
    Require all granted
    RewriteEngine On
    RewriteCond %{THE_REQUEST} /([^.]+)'.php [NC]
    RewriteRule ^ /%1 [NC,L,R]
    <Files "*.php">
        MultiviewsMatch Any
    </Files>
</Directory>

然后保存文件并重新启动Apache sudo systemctl restart apache2

当您在apache2.conf中声明更多指令时,对每个指令重复Multiviews指令:

<Directory /var/www/html/example.com/>
  Options FollowSymLinks Multiviews
  AllowOverride All
  Require all granted
</Directory>

确保启用/取消注释apache2.conf:中的重写协商模块

LoadModule rewrite_module modules/mod_rewrite.so
LoadModule negotiation_module mod_negotiation.so