漂亮的URL条件重写

时间:2017-03-31 04:02:53

标签: php apache .htaccess mod-rewrite

我们的网站允许一个漂亮的网址'etest.me/1234',其中'1234'是客户端ID。如下所示,它重定向到我们的route.php文件,我们在其中进行重定向。问题是当客户端使用'etest.me'而不使用'/ 1234'时他们会得到apache'在此服务器上找不到请求的URL / go /。'信息。我希望当'/ 1234'丢失时,网址会转到另一个页面。

请注意,我们将域和路径转发到不存在的“/ go”目录,因此下面的规则将捕获它。以下内容位于根目录中的.htaccess文件中。

RewriteEngine On
#restrict rewriting URLs ONLY to paths that DO NOT exist
RewriteCond %{SCRIPT_FILENAME} !-d
# commented out to speed up looking since we are not processig file names anyway
#RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^go/([a-zA-Z0-9/]+)$ ./route\.php?go=$1

3 个答案:

答案 0 :(得分:2)

对我来说工作得很好。希望这对你也有用。

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9]+)$ /route.php?go=$1 //when client id exist
RewriteRule ^([a-zA-Z0-9]+)$ /index.php // when no client id

答案 1 :(得分:0)

您可以添加新规则来处理这种情况:

RewriteRule ^go/$ ./another_script\.php

答案 2 :(得分:0)

我接受了Sahil的回答并发布了以下整个逻辑供其他人使用:

Domain: etest.me
Pretty URL: etest.me/1234 (where '1234' is a client id)
Forwarded to: etesting.io/go (with forward path option selected so the '/1234' will be include in the forward)

注意:服务器上没有'/ go'目录,'/ go'用于触发重定向。

想要'etest.me'(没有客户端ID)转到根目录中的索引文件。

以下是.htaccess中的重写规则:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9/]*)$ ./route\.php?go=$1 

这是route.php代码:

<?php

if($_GET['go']){
    $a = explode('/', $_GET['go']);
    $c = count($a);
    if($c == 1 || $c == 2){
        header('location: ../../index.php?aid=' . $a[0] . '&tid=' . $a[1]);
        exit;
    }
    else{
        die('Invalid URL');
    }
}
else{
    header('location: ../index.php');
    exit;
}

最后是index.php文件:

if($_GET['aid'] && $_GET['tid']){
    header('location: test/register.php?aid=' . $_GET['aid'] . '&tid=' . $_GET['tid']);
    exit;
}
elseif($_GET['aid']){
    header('location: test/index.php?aid=' . $_GET['aid']);
    exit;
}
else{
    header('location: account/index.php?' . $_SERVER['QUERY_STRING']);
    exit;
}

希望这有助于将来的某些人。

我想要一个更优雅的解决方案,但它现在已经落后于我了......

相关问题