.htaccess重写GET变量

gkn4icbw  于 2023-08-06  发布在  其他
关注(0)|答案(8)|浏览(106)

我有一个index.php处理所有的路由index.php?page=controller(简化)只是为了将逻辑与视图分开。

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w\d~%.:_\-]+)$ index.php?page=$1 [NC]

字符串
基本上就是:http://localhost/index.php?page=controller
http://localhost/controller/
谁能帮我添加重写
http://localhost/controller/param/value/param/value(等等)
这将是:
http://localhost/controller/?param=value&param=value
我不能让它和重写规则一起工作。
一个控制器可能看起来像这样:

<?php
if (isset($_GET['action'])) {
 if ($_GET['action'] == 'delete') {
do_Delete_stuff_here();
}
}
?>


还有:

<?php
if (isset($_GET['action']) && isset($_GET['x'])) {
 if ($_GET['action'] == 'delete') {
do_Delete_stuff_here();
}
}
?>

hl0ma9xz

hl0ma9xz1#

基本上,人们试图说的是,你可以这样做一个重写规则:

RewriteRule ^(.*)$ index.php?params=$1 [NC, QSA]

字符串
这将使您的实际php文件如下所示:

index.php?params=param/value/param/value


你的URL应该是这样的:

http://url.com/params/param/value/param/value


在你的PHP文件中,你可以通过像这样展开来访问你的参数:

<?php

$params = explode( "/", $_GET['params'] );
for($i = 0; $i < count($params); $i+=2) {

  echo $params[$i] ." has value: ". $params[$i+1] ."<br />";

}

?>

xa9qqrwz

xa9qqrwz2#

我认为最好将所有请求重定向到index.php文件,然后使用php提取控制器名称和任何其他参数。与其他框架一样,如Zend Framework。
这是一个简单的类,可以做你想要的。

class HttpRequest
{
    /**
     * default controller class
     */
    const CONTROLLER_CLASSNAME = 'Index';

    /**
     * position of controller
     */
    protected $controllerkey = 0;

    /**
     * site base url
     */
    protected $baseUrl;

    /**
     * current controller class name
     */
    protected $controllerClassName;

    /**
     * list of all parameters $_GET and $_POST
     */
    protected $parameters;

    public function __construct()
    {
        // set defaults
        $this->controllerClassName = self::CONTROLLER_CLASSNAME;
    }

    public function setBaseUrl($url)
    {
        $this->baseUrl = $url;
        return $this;
    }

    public function setParameters($params)
    {
        $this->parameters = $params;
        return $this;
    }

    public function getParameters()
    {
        if ($this->parameters == null) {
            $this->parameters = array();
        }
        return $this->parameters;
    }

    public function getControllerClassName()
    {
        return $this->controllerClassName;
    }

    /**
     * get value of $_GET or $_POST. $_POST override the same parameter in $_GET
     * 
     * @param type $name
     * @param type $default
     * @param type $filter
     * @return type 
     */
    public function getParam($name, $default = null)
    {
        if (isset($this->parameters[$name])) {
            return $this->parameters[$name];
        }
        return $default;
    }

    public function getRequestUri()
    {
        if (!isset($_SERVER['REQUEST_URI'])) {
            return '';
        }

        $uri = $_SERVER['REQUEST_URI'];
        $uri = trim(str_replace($this->baseUrl, '', $uri), '/');

        return $uri;
    }

    public function createRequest()
    {
        $uri = $this->getRequestUri();

        // Uri parts
        $uriParts = explode('/', $uri);

        // if we are in index page
        if (!isset($uriParts[$this->controllerkey])) {
            return $this;
        }

        // format the controller class name
        $this->controllerClassName = $this->formatControllerName($uriParts[$this->controllerkey]);

        // remove controller name from uri
        unset($uriParts[$this->controllerkey]);

        // if there are no parameters left
        if (empty($uriParts)) {
            return $this;
        }

        // find and setup parameters starting from $_GET to $_POST
        $i = 0;
        $keyName = '';
        foreach ($uriParts as $key => $value) {
            if ($i == 0) {
                $this->parameters[$value] = '';
                $keyName = $value;
                $i = 1;
            } else {
                $this->parameters[$keyName] = $value;
                $i = 0;
            }
        }

        // now add $_POST data
        if ($_POST) {
            foreach ($_POST as $postKey => $postData) {
                $this->parameters[$postKey] = $postData;
            }
        }

        return $this;
    }

    /**
     * word seperator is '-'
     * convert the string from dash seperator to camel case
     * 
     * @param type $unformatted
     * @return type 
     */
    protected function formatControllerName($unformatted)
    {
        if (strpos($unformatted, '-') !== false) {
            $formattedName = array_map('ucwords', explode('-', $unformatted));
            $formattedName = join('', $formattedName);
        } else {
            // string is one word
            $formattedName = ucwords($unformatted);
        }

        // if the string starts with number
        if (is_numeric(substr($formattedName, 0, 1))) {
            $part = $part == $this->controllerkey ? 'controller' : 'action';
            throw new Exception('Incorrect ' . $part . ' name "' . $formattedName . '".');
        }
        return ltrim($formattedName, '_');
    }
}

字符串

使用方法:

$request = new HttpRequest();
$request->setBaseUrl('/your/base/url/');
$request->createRequest();

echo $request->getControllerClassName(); // return controller name. Controller name separated by '-' is going to be converted to camel case.
var_dump ($request->getParameters());    // print all other parameters $_GET & $_POST

.htaccess文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

rt4zxlrg

rt4zxlrg3#

重写规则将传递整个URL:

RewriteRule ^(.*)$ index.php?params=$1 [NC]

字符串
你的index.php会将完整路径解释为controller/param/value/param/value(我的PHP有点生疏):

$params = explode("/", $_GET['params']);
if (count($params) % 2 != 1) die("Invalid path length!");

$controller = $params[0];
$my_params = array();
for ($i = 1; $i < count($params); $i += 2) {
  $my_params[$params[$i]] = $params[$i + 1];
}

mkh04yzy

mkh04yzy4#

重定向到index.php?params=param/value/param/value,让php拆分整个$_GET['params']怎么样?我认为这是WordPress处理它的方式。

a9wyjsp7

a9wyjsp75#

出于某种原因,选择的解决方案对我不起作用。它将始终只返回“index.php”作为参数的值。
经过一些尝试和错误,我发现下面的规则工作得很好。假设您希望yoursite.com/somewhere/var1/var2/var3指向yoursite.com/somewhere/index.php?params= var 1/var 2/var 3,然后将以下规则放置在“somewhere”目录下的.htaccess文件中:

Options +FollowSymLinks
RewriteEngine On
# The first 2 conditions may or may not be relevant for your needs
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-f
# This rule converts your flat link to a query
RewriteRule ^(.*)$ index.php?params=$1 [L,NC,NE]

字符串
然后,在PHP或您选择的任何语言中,只需使用@Wesso指出的explode命令将值分开。
出于测试目的,这在index.php文件中应该足够了:

if (isset($_GET['params']))
{
    $params = explode( "/", $_GET['params'] );
    print_r($params);
    exit("YUP!");
}

fcy6dtqo

fcy6dtqo6#

这是你要找的吗
这个例子演示了如何使用循环标志轻松隐藏查询字符串参数。假设您有一个类似http://www.mysite.com/foo.asp?a=A&b=B&c=C的URL,并且希望以http://www.myhost.com/foo.asp/a/A/b/B/c/C的身份访问它
尝试以下规则以获得预期结果:
第一个月

dhxwm5r4

dhxwm5r47#

你确定你使用的是Apache服务器,.htaccess只在Apache服务器上工作。如果你使用的是IIS,那么需要web.config。在这种情况下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
        <rule name="Homepage">
                    <match url="Homepage"/>
                    <action type="Rewrite" url="index.php" appendQueryString="true"/>
                </rule>
</rules>
        </rewrite>

        <httpErrors errorMode="Detailed"/>
        <handlers>
            <add name="php" path="*.php" verb="*" modules="IsapiModule" scriptProcessor="C:\Program Files\Parallels\Plesk\Additional\PleskPHP5\php5isapi.dll" resourceType="Unspecified"/>
        </handlers>



    </system.webServer>
</configuration>

字符串

w8ntj3qf

w8ntj3qf8#

使用QSA
blabla.php?originialquery=333 RewriteRule ^blabla.php index.php?addnewquery1=111&addnewquery2=222 [L,NC,QSA]您将获得所有111,222,333

相关问题