Mod Rewrite-有更快的方法吗? [英] Mod Rewrite - is there a faster way?

查看:102
本文介绍了Mod Rewrite-有更快的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im建立一个包含很多参数的网站.目前,我在.htaccess文件中使用以下代码:

im building a site with lots of parameters. At the moment i'm using this Code in my .htaccess file:

Options +FollowSymLinks
RewriteEngine on
RewriteBase /epo

RewriteRule (.*)/(.*)/(.*)/(.*)/(.*)/$ index.php?section=$1&content=$2&site=$3&param=$4&param2=$5 [QSA]
RewriteRule (.*)/(.*)/(.*)/(.*)/$ index.php?section=$1&content=$2&site=$3&subsite=$4 [QSA]
RewriteRule (.*)/(.*)/(.*)/$ index.php?section=$1&content=$2&site=$3 [QSA]
RewriteRule (.*)/(.*)/$ index.php?section=$1&content=$2 [QSA]
RewriteRule (.*)/$ index.php?section=$1 [QSA]

RewriteCond %{REQUEST_URI} ^/[^\.]+[^/]$
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]

我是mod_rewrite的新手,这就是为什么这段代码很乱的原因.有没有更好的方法来处理所有这些参数?最后两行仅在末尾添加一个"/"(以防万一).如果有人可以解释他们的代码,那也很棒,这样我就可以理解我做错了:)

I'm new to mod_rewrite, thats why this code is a mess. Is there any better way to deal with all these parameters? The last two lines are just there to add a "/" at the end in case there is none. Would be also great if someone could explain their code, so i can understand what i did wrong :)

推荐答案

与Hugo的示例类似,但没有GET param:

It is similar to Hugo's example but without GET param:

<IfModule mod_rewrite.c>
    SetEnv HTTP_MOD_REWRITE On
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^.*$ index.php [NC,L]
</IfModule>

PHP中,您可以执行以下操作:

in PHP you can do following:

$pathInfo = pathinfo($_SERVER['SCRIPT_NAME']);
$baseUrl = $pathInfo['dirname'];
$baseFile = $pathInfo['basename'];
$url = rtrim(str_replace([$baseUrl, '/'.$baseFile], '', $_SERVER['REQUEST_URI']), '/');
$method = strtolower($_SERVER['REQUEST_METHOD']);
$isModRewrite = array_key_exists('HTTP_MOD_REWRITE', $_SERVER);

您的网址现在看起来像:

Your url's can now look something like:

http://www.yourserver.com/param1/param2

或(如果未启用mod重写)

OR (if mod rewrite is not enabled)

http://www.yourserver.com/index.php/param1/param2

在两种方式下,$url变量看起来都像/param1/param2

In both ways the $url variable looks like /param1/param2

您可以在此字符串上执行explode,或使用此字符串提供PHP路由库以提取参数.

You can do explode on this string or feed a PHP routing library with this string for extracting your parameters.

PHP路由示例库:

https://github.com/robap/php-router

https://github.com/deceze/Kunststube-Router

这篇关于Mod Rewrite-有更快的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆