【问题标题】:How to control url page with htaccess and get parameter in index如何使用 htaccess 控制 url 页面并在索引中获取参数
【发布时间】:2018-01-02 03:40:19
【问题描述】:

如何用htaccess控制url页面并在index页面中获取参数但url中不显示“index”,例如:

1)mydomain is "papashop.com"

2).htaccess :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^([^/]+)/?$ $1.php [L]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
RewriteRule ^([^/]+)/([^/]+)/?$ $1.php?var1=$2 [L,QSA]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ $1.php?var1=$2&var2=$3 [L,QSA]

3)code at contact.php :
<a href="page-alfa">Page Alfa</a>   ==> www.papashop.com/page-alfa 

4)code at index.php :
<?php  
$idpage=$_GET['var1'];  
if($idpage != ''){
  echo 'show content from query string url';
}else{
  echo 'content normal from index web';
}
?>

注意:

1)true: papashop.com/page-alfa => 不工作/找不到页面。 (我想要这个)

2)false: papashop.com/index/page-alfa => 这是我在 index.php 中的代码(但我不想这样)

3)我没有 page-alfa.php 文件,在控制面板中只有 index.php 和 contact.php。

谢谢

【问题讨论】:

    标签: php html .htaccess


    【解决方案1】:

    试试这个:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    

    这会将所有请求路由到 index.php。

    1: papashop.com/page-alfa 将是真的 2: papashop.com/index/page-alfa 也是如此。

    要在代码中获取请求的 url,试试这个:

    <?php
    
        $request_uri = trim(explode('?', $_SERVER['REQUEST_URI'])[0], '/');
        $query_string = $_SERVER['QUERY_STRING'];
    
        // JUST MORE EXAMPLE
        $   $requests = explode('/', $request_uri);
    
        if(empty($requests) || count($requests) == 0){
            // This is ordinary papashop.com. This is index page.
        } else {
            if($requests[0] == 'page-alfa'){
                // Show page alfa.
            } else if($requests[0] == 'contact' && $requests[1] == 'phone'){
                // URL is papashop.com/contact/phone 
            }
            // etc...
        }
    
    ?>
    

    更新: 如果您在本地主机上,RewriteBase 将类似于 /site_root/

    【讨论】:

    • 不工作,总是重定向到仪表板 apache。 =(
    • 看起来您在本地主机上(XAMPP 或 WAMP 等)。我更新了我的答案以显示如何解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2012-05-29
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多