简体   繁体   English

如何处理 .htaccess 规则中的特殊字符,如 : 和 , ?

[英]How to handle special characters like : and , in .htaccess rules?

How i can get a and b values from urls like this:我如何从这样的网址获取ab值:

http://127.0.0.1:8080/a:4522,b:846

I add this code to .htaccess for redirect all links to index.php but not working when use : and , character我将此代码添加到 .htaccess 以将所有链接重定向到 index.php 但在使用:,字符时不起作用

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

For http://127.0.0.1:8080/a:4522,b:846 the request URI equals to /a:4522,b:846 .对于http://127.0.0.1:8080/a:4522,b:846请求 URI 等于/a:4522,b:846 And the .htaccess directives put the request URI into path GET parameter. .htaccess指令将请求 URI 放入path GET 参数中。 So you can simply parse $_GET['path'] in PHP:所以你可以简单地在 PHP 中解析$_GET['path']

<?php
$vars = [];
if ($path = isset($_GET['path']) ? $_GET['path'] : null) {
  foreach (explode(',', $path) as $part) {
    $tmp = explode(':', $part);
    if (count($tmp) == 2) {
      $vars[$tmp[0]] = $tmp[1];
    }
  }
}
var_dump($vars);

Output输出

array(2) {
  ["a"]=>
  string(4) "4522"
  ["b"]=>
  string(3) "846"
}

Sample configuration示例配置

/etc/apache2/vhosts.d/01_test_vhost.conf /etc/apache2/vhosts.d/01_test_vhost.conf

<VirtualHost 127.0.0.12:80>
  ServerName apache-test.local
  ServerAdmin root@localhost
  DocumentRoot "/var/www/apache-test.local/public"

  ErrorLog "/var/www/apache-test.local/logs/error.log"
  CustomLog "/var/www/apache-test.local/logs/access.log" common

  <Directory "/var/www/apache-test.local/public">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [L]
    SetHandler application/x-httpd-php
  </Directory>
</VirtualHost>

/var/www/apache-test.local/public/.htaccess /var/www/apache-test.local/public/.htaccess

Just as in your question.就像你的问题一样。

/var/www/apache-test.local/public/index.php /var/www/apache-test.local/public/index.php

The PHP code above.上面的PHP代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM