.htaccess动态清理URL

时间:2014-07-30 19:06:24

标签: php html .htaccess mod-rewrite

我一直在寻找很长时间,如何制作干净的网址,但我似乎无法找到问题的答案。

这是index.php中的PHP设置:

<?php
    $page = $_GET["page"];

    if(file_exists("pages/{$page}.php")) {
        include ("pages/{$page}.php");
    } else if (empty($page)) {
        include ("pages/Home.php");
    } else {
        echo "This page do not exist";
    }
?>

这是我的HTML:

<ul>
    <li>
        <a href="Home">Home</a> <!-- Regular navigation link for: Home, About, Contact -->
    </li><li>
        <a href="Project/2">Project</a> <!-- The link I press to see a project -->
    </li>
</ul>

这是我的.htaccess

RewriteEngine On

RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d

RewriteRule ^(.*)$ index.php?page=$1
#RewriteRule ^(.*)/(.*)$ index.php?page=$1&id=$2

Options -Indexes

它完美地重写了我的网址 的 FROM:     domain.com/index.php?page=Home.php     domain.com/Home

两个重写规则完全分离,但不能在一起。我怎样才能使这两者相互配合?

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

RewriteEngine On

RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d

RewriteRule ^(.*)/(.*)$ index.php?page=$1&id=$2
RewriteRule ^(.*)$ index.php?page=$1

Options -Indexes

还有一件事,你应该使用$_GET代替_GET

答案 1 :(得分:0)

.htaccess正在销毁$ _GET值,请改为尝试:

<?php

# From the URI, get whatever is after the last slash:
$subject = $_SERVER['REQUEST_URI'];
$pattern = '/.*\/(.*)$/';
preg_match($pattern, $subject, $matches);
$page = $matches[1];

if(file_exists("pages/{$page}.php")) {
    include ("pages/{$page}.php");
} else if (empty($page)) {
    include ("pages/Home.php");
} else {
    echo "This page do not exist";
}
?>